如何在python中调用同一个类内的静态方法

Hao*_* Yu 9 python

我在同一个类中有两个静态方法

class A:
    @staticmethod
    def methodA():
        print 'methodA'

    @staticmethod
    def methodB():
        print 'methodB'
Run Code Online (Sandbox Code Playgroud)

我怎么能打电话给methodA里面methodB?self似乎在静态方法中不可用.

小智 10

实际上,self静态方法不可用.如果使用装饰@classmethod而不是@staticmethod第一个参数,则会引用类本身(通常命名为cls).但尽管如此,在静态方法中,methodB()您可以methodA()直接通过类名访问静态方法:

@staticmethod
def methodB():
    print 'methodB'
    A.methodA()
Run Code Online (Sandbox Code Playgroud)


Jin*_* He 9

正如@Ismael Infante 所说,您可以使用@classmethod装饰器。

class A:
    @staticmethod
    def methodA():
        print 'methodA'

    @classmethod
    def methodB(cls):
        cls.methodA()
Run Code Online (Sandbox Code Playgroud)

  • @JamesCarter如果你使用classmeethod,你会得到cls变量,它引用包含类本身,所以你可以使用这个“cls”来引用类及其资源(方法,属性)。如果使用staticmethod,则只能使用类名来引用类,而如果在子类中,继承了父类的静态方法,则静态方法中的类名仍然是父类名... (2认同)