Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将变量作为参数返回给方法的正确方法_Python - Fatal编程技术网

Python 将变量作为参数返回给方法的正确方法

Python 将变量作为参数返回给方法的正确方法,python,Python,一个令人困惑的问题 我在一个类中有两个方法: from example import sample2 class sample1: def m1(): a='apple' b='ball' return sample2.m3(a,b) def m2(): a='ant' b='bat' c='cat' return sa

一个令人困惑的问题

我在一个类中有两个方法:

from example import sample2
class sample1:
      def m1():
           a='apple'
           b='ball'
           return sample2.m3(a,b)
      def m2():
           a='ant'
           b='bat'
           c='cat'
           return sample2.m3(a,b,c)
在example.py中:

class sample2:
       def m3("here I want to access any `a`,`b`,`c` of respective m1 and m2"):
            .....
 class sample2:
       def m3(a,b):
           print(a)   
如果这个问题没有意义,我很抱歉,但当我尝试访问此项时,仅作为:

class sample1:
      def m1():
           a='apple'
           b='ball'
           return sample2.m3(a,b)
在example.py中:

class sample2:
       def m3("here I want to access any `a`,`b`,`c` of respective m1 and m2"):
            .....
 class sample2:
       def m3(a,b):
           print(a)   

a
有值
apple
,所以类似的方式,为什么我不能从特定的
m1
m2
返回中访问a、b、c的任何值?

Python中的变量总是应用于特定的范围,例如类、函数或闭包。Python使用,这意味着只能通过嵌套在源代码中来连接作用域。最重要的是,不同范围内的变量根本没有连接

当你“传递一个变量”给一个函数时,你实际上只传递了一个值。该变量不存在于其他函数中(除非嵌套),也不存在于周围的作用域中

def nested(a):
    a = 3
    print('a =', a)  # a = 3

def parent():
    a = 4
    nested(a)
    print('a =', a)  # a = 4

parent()
print(a)  # NameError: name 'a' is not defined
函数应主要通过调用输入和返回结果来交换数据:

def nested(a):       # receive input
    a = 3
    print('a =', a)  # a = 3
    return a         # return output

def parent():
    a = 4
    a = nested(a)    # replace a with result of nested(a)
    print('a =', a)  # a = 3

parent()
请注意,只传入和返回值。如果在两个函数中重命名
a
,上述行为可能完全相同


使用类实例时,实例本身作为命名空间(类似于作用域)。该实例的方法可以通过修改实例的属性来交换数据。实例始终作为第一个参数传递给方法:

class Example():
    """An example for setting attributes on an instance"""
    def __init__(self):
        self.a = 0

    def nested(self):
        self.a = 3
        print('self.a =', self.a)  # self.a = 3

    def parent(self):
        self.a = 4
        print('self.a =', self.a)  # self.a = 4
        self._nested()
        print('self.a =', self.a)  # self.a = 3

instance = Example()
print(instance.a)  # 0
instance.parent()  # self.a = 4
                   # self.a = 3
要在对象之间交换数据,方法还应主要通过调用输入和返回结果来交换数据:

class Example():
    """An example for setting attributes on an instance"""
    def __init__(self, a):
        self.a = a

    def multiply(self, value):
        return self.a * value

instance = Example(6)
print(instance.multiply(10))  # 60

这就是你如何使用装饰器。有关decorator工作原理的更多信息,请参见以下示例:
我建议您首先尝试更好地理解类和对象的概念。示例教程:
这篇文章还可以帮助您了解staticmethod decorator的工作原理-

示例.py文件及其说明:

class sample2:
    @staticmethod
    def m3(a, b, c=None): # it works exactly the same as m3 function that is outside the class
        print(a)
        # this can be used without creating an object of sample2 class, example:
        # sample2.m3(a="apple, b="ball")

    def m3_method(self, a, b): # this one requires object on which it can be called
        print(a)
        # you have access to sample2 class object via self parameter, example of code:
        # sample2_object = sample2() # you create object of sample2 class here
        # sample2_object.m3_method(a="apple", b="ball") # you call m3_method on sample2_object here


def m3(a, b, c=None): # default value of c is add so you can either call it with 2 or 3 arguments
    # example calls:
    # m3("a", "b")
    # m3("a", "b", "c")
    print(a)

您应该能够运行这段代码,我认为这会让您了解如何使用Python类。

请注意,
m1
中的变量
a
m2
中的
m2
中的变量不同,即使它们具有相同的值。即使将
m1:a
传递给
m2:a
也只是在交换值,而不是变量。很抱歉,这是返回样本2。m3(a,b)我已经编辑过,所以您想更改函数m3中a,b和c的值吗?@MohammadClassal not change,但是我想访问m3中的a='ant',但是
a
有两个值'apple'和'ant',这两个值都是从
m2
m1
返回的,它们是不同的a。您没有访问相同的a。为了完整性,也许您可以在答案中引入可选变量。由于op使用不同数量的参数调用
sample2.m3
,因此她必须至少使用
c
作为可选参数,或者只使用*args@SembeiNorimaki我不确定这是否是OP难以理解的——如果不是,那将是一个不必要的复杂问题。这是可以理解的,但是我想把它们作为参数传递给另一个方法@Sophie将参数传递给函数、同一类的方法或另一类的方法的工作原理相同。它实际上是相同的机制。我可以知道如何通过一个例子来实现这一点吗?因此,在sample2 m3中,当我们返回相同的
a
时,我们不能访问任何类似的def m3(a、b、c中的任何一个),因为我们返回的是不同的值,并且可能没有任何重写,我猜哦,我没有注意到您可能需要使用2或3个参数。还有一种方法可以做到这一点。让我来做编辑。看看m3函数定义——函数“重载”有python的方式。因此,它可以用3个或2个参数调用(如果没有给出参数,它将有默认值-在这种情况下没有)。我希望在需要时可以访问class='ant'和class='apple'。这可能吗?很抱歉,但我不明白你想说什么。我已经修复了您一直在努力解决的语法错误,但我需要更多关于您正在尝试实现的内容的详细信息,以帮助您获得更多。如果你能一步一步地描述什么是切入点以及你想要实现什么,那么我可能能够帮助你进行代码返工。正如你提到的方法重载,如果有一些方法,比如m1,比如m4,并且对
a
b
有不同的值,那么打印
a
会给我带来@staticmethod def m4():a='aqua'b='bill'返回sample2.m3(a,b)