Haoliang Yu
Haoliang Yu

Reputation: 3097

How to call static methods inside the same class in python

I have two static methods in the same class

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

    @staticmethod
    def methodB():
        print 'methodB'

How could I call the methodA inside the methodB? self seems to be unavailable in the static method.

Upvotes: 30

Views: 24864

Answers (3)

matt.baker
matt.baker

Reputation: 256

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

    @staticmethod
    def methodB():
        print 'methodB'
        __class__.methodA()

Upvotes: 1

Jing He
Jing He

Reputation: 914

As @Ismael Infante says, you can use the @classmethod decorator.

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

    @classmethod
    def methodB(cls):
        cls.methodA()

Upvotes: 9

Ismael Infante
Ismael Infante

Reputation: 532

In fact, the self is not available in static methods. If the decoration @classmethod was used instead of @staticmethod the first parameter would be a reference to the class itself (usually named as cls). But despite of all this, inside the static method methodB() you can access the static method methodA() directly through the class name:

@staticmethod
def methodB():
    print 'methodB'
    A.methodA()

Upvotes: 33

Related Questions