是否可以从另一个静态方法中调用静态方法?
我试过这个:
class MyClass(object):
@staticmethod
def static_method_1(x):
x = static_method_2(x)
print x
@staticmethod
def static_method_2(x):
return 2*x
Run Code Online (Sandbox Code Playgroud)
这回来了
NameError: name 'static_method_2' is not defined
Run Code Online (Sandbox Code Playgroud)
Staticmethods通过类调用:MyClass.static_method_2(x).
你可能根本不需要静态方法,而是一种类方法.这些被称为相同的方式,但获得对类的引用,然后您可以使用它来调用另一个方法.
class MyClass(object):
@classmethod
def static_method_1(cls, x):
x = cls.static_method_2(x)
print x
@classmethod
def static_method_2(cls, x):
return 2*x
Run Code Online (Sandbox Code Playgroud)
请注意,在Python中你不会这样做.除非存储状态,否则通常没有理由拥有一个类.这些可能都是最好的独立功能.