Jos*_*and 2 python methods static-methods
我有一个具有静态方法的类,我想在该类中使用另一个静态方法来调用该方法,但它返回NameError: name ''method_name' is not defined
我正在尝试做的事情的例子。
class abc():
@staticmethod
def method1():
print('print from method1')
@staticmethod
def method2():
method1()
print('print from method2')
abc.method1()
abc.method2()
Run Code Online (Sandbox Code Playgroud)
输出:
print from method1
Traceback (most recent call last):
File "test.py", line 12, in <module>
abc.method2()
File "test.py", line 8, in method2
method1()
NameError: name 'method1' is not defined
Run Code Online (Sandbox Code Playgroud)
解决这个问题的最佳方法是什么?
我想将代码保留为这种格式,其中有一个类包含这些静态方法并使它们能够相互调用。
小智 5
它不起作用,因为method1它是类的属性abc,而不是在全局范围内定义的东西。
您必须通过直接引用该类来访问它:
@staticmethod
def method2():
abc.method1()
print('print from method2')
Run Code Online (Sandbox Code Playgroud)
或者使用类方法而不是静态方法,这将使方法能够访问其类对象。我推荐使用这种方式。
@classmethod
def method2(cls): # cls refers to abc class object
cls.method1()
print('print from method2')
Run Code Online (Sandbox Code Playgroud)