Par*_*eog 2 python function self python-3.x
采用以下简化示例.
class A(object):
variable_A = 1
variable_B = 2
def functionA(self, param):
print(param+self.variable_A)
print(A.functionA(3))
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我收到以下错误
Traceback (most recent call last):
File "python", line 8, in <module>
TypeError: functionA() missing 1 required positional argument: 'param'
Run Code Online (Sandbox Code Playgroud)
但是,如果我删除self,在函数声明中,我无法访问变量variable_A和variable_B类,我得到以下错误
Traceback (most recent call last):
File "python", line 8, in <module>
File "python", line 6, in functionA
NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)
那么,我如何访问类变量而不是在这里得到param错误?我正在使用Python 3 FYI.
您必须首先创建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))
Run Code Online (Sandbox Code Playgroud)
如果您不想使用实例,可以使用staticmethod装饰器.静态方法是方法的特例.有时,您将编写属于某个类的代码,但根本不使用该对象本身.
class A(object):
variable_A = 1
variable_B = 2
@staticmethod
def functionA(param):
return (param+A.variable_A)
print(A.functionA(3))
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用classmethod装饰器.类方法是不绑定到对象的方法,而是绑定到类的方法!
class A(object):
variable_A = 1
variable_B = 2
@classmethod
def functionA(cls,param):
return (param+cls.variable_A)
print(A.functionA(3))
Run Code Online (Sandbox Code Playgroud)