简体   繁体   English

如何将参数传递给第一个参数是self的python函数?

[英]How to pass arguments to python function whose first parameter is self?

Take the following simplified example.以下面的简化示例为例。

class A(object):
    variable_A = 1
    variable_B = 2

    def functionA(self, param):
        print(param+self.variable_A)

print(A.functionA(3))

In the above example, I get the following error在上面的示例中,我收到以下错误

Traceback (most recent call last):
  File "python", line 8, in <module>
TypeError: functionA() missing 1 required positional argument: 'param'

But, if I remove the self , in the function declaration, I am not able to access the variables variable_A and variable_B in the class, and I get the following error但是,如果我在函数声明中删除self ,则无法访问类中的变量variable_Avariable_B ,并且出现以下错误

Traceback (most recent call last):
  File "python", line 8, in <module>
  File "python", line 6, in functionA
NameError: name 'self' is not defined

So, how do I access the class variables and not get the param error here?那么,我如何访问类变量而不是在这里得到 param 错误? I am using Python 3 FYI.我正在使用 Python 3 仅供参考。

You must first create an instance of the class A您必须首先创建类 A 的实例

class A(object):
    variable_A = 1
    variable_B = 2

    def functionA(self, param):
        return (param+self.variable_A)


a = A()
print(a.functionA(3))

You can use staticmethod decorator if you don't want to use an instance.如果您不想使用实例,可以使用 staticmethod 装饰器。 Static methods are a special case of methods.静态方法是方法的一种特殊情况。 Sometimes, you'll write code that belongs to a class, but that doesn't use the object itself at all.有时,您会编写属于一个类的代码,但它根本不使用对象本身。

class A(object):
    variable_A = 1
    variable_B = 2

    @staticmethod
    def functionA(param):
        return (param+A.variable_A)

print(A.functionA(3))

Another option is to use classmethod decorator.另一种选择是使用 classmethod 装饰器。 Class methods are methods that are not bound to an object, but to a class!类方法是不绑定到对象,而是绑定到类的方法!

class A(object):
    variable_A = 1
    variable_B = 2

    @classmethod
    def functionA(cls,param):
        return (param+cls.variable_A)

print(A.functionA(3))

functionA in your snippet above is an instance method.上面代码片段中的functionA是一个实例方法。 You do not pass "self" directly to it.您不会将“自我”直接传递给它。 Instead, you need to create an instance in order to use it.相反,您需要创建一个实例才能使用它。 The "self" argument of the function is, in fact, the instance it's called on.函数的“self”参数实际上是它被调用的实例。 Eg:例如:

a = A()
a.functionA(3)

PS Note that your functionA calls print but doesn't return anything, meaning it implicitly returns None . PS 请注意,您的functionA调用print但不返回任何内容,这意味着它隐式返回None You should either have it return a value and print it from the caller, or, as I have done above, call it and let it print on its own.您应该让它返回一个值并从调用方打印它,或者,正如我上面所做的那样,调用它并让它自己打印。

Create an object of A first.先创建一个A的对象。

a = A()
a.functionA(3)

When a function object (what the def statement creates) is an attribute of a class AND is looked up (using the obj.attrname scheme) on the class or an instance of the class, it gets turned into a method object.当一个函数对象( def语句创建的)是一个类的一个属性obj.attrname在该类或该类的一个实例上查找(使用obj.attrname方案)时,它就会变成一个method对象。 This method object is itself a callable.这个method对象本身是一个可调用对象。 If the lookup happens on an instance, this instance will be "magically" inserted as the first argument to the function.如果查找发生在一个实例上,这个实例将“神奇地”作为函数的第一个参数插入。 If not, you will have to provide it by yourself (just like you would for any other argument).如果没有,您将不得不自己提供它(就像您提供任何其他参数一样)。

You can read more about this (and how the "magic" happens here: https://wiki.python.org/moin/FromFunctionToMethod你可以阅读更多关于这个(以及“魔法”是如何在这里发生的: https : //wiki.python.org/moin/FromFunctionToMethod

In your case, you lookup the function on the class, so it expects two arguments ( self and param ), but you only pass param , hence the error.在您的情况下,您在类上查找函数,因此它需要两个参数( selfparam ),但您只传递param ,因此出现错误。

You defined variable_A and variable_B as class attributes (attributes that will be shared between all instances of the class).您将variable_Avariable_B定义为类属性(将在类的所有实例之间共享的属性)。 If that's really the intention, and you want a method you can call on the class itself and that will be able to access class attributes, you can make functionA a classmethod (it works the same as an "instance" method except it's the class that is 'magically' inserted as first argument):如果这真的是意图,并且您想要一个可以在类本身上调用并且能够访问类属性的方法,则可以将functionA设为类classmethod (它与“实例”方法的工作方式相同,只是它是被“神奇地”作为第一个参数插入):

class A(object):
  variable_A = 1
  variable_B = 2

  @classmethod
  def functionA(cls, param):
    return param + cls.variable_A

Then you can call functionA either directly on the class itself:然后你可以直接在类本身上调用functionA

print(A.functionA(42))

or on an instance if you already have one at hand:或者在一个实例上,如果你已经有了一个:

a = A()

# ...

print(a.functionA(42))

Now if you really wanted variable_A and variable_B to be per-instance attributes (each instance of A has it's own distinct variables), you need to 1/ create those attributes on the instance itself in the initialier method and 2/ call functionA on some A instance, ie:现在,如果您真的希望variable_Avariable_B成为每个实例的属性( A每个实例都有自己独特的变量),您需要 1/ 在初始化方法中在实例本身上创建这些属性,2/ 在某些A上调用functionA实例,即:

class A(object):
    def __init__(self, variable_A=1, variable_B=2):
        self.variable_A = variableA
        self.variable_B = variableB

  def functionA(self, param):
    return param + self.variable_A



a1 = A() # using default values
print(a1.functionA(42))

a2 = A(5) # custom value for variable_A
print(a2.functionA(42))
class A(object):
    variable_A = 1
    variable_B = 2

    def functionA(self, param):
        print(param+self.variable_A)

A().functionA(3)

A() is calling the class to create an instance A() 正在调用类来创建实例

4

[Program finished]

You can use return in function and then print at last.您可以在函数中使用 return ,然后最后打印。 Posting this answer as per OP template , accepted answers and other answers are recommended way to do it.根据 OP 模板发布此答案,建议采用已接受的答案和其他答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM