How to call static methods inside the same class in python

Question:

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.

Asked By: Haoliang Yu

||

Answers:

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()
Answered By: Ismael Infante

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

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

    @classmethod
    def methodB(cls):
        cls.methodA()
Answered By: Jing He
class A:
    @staticmethod
    def methodA():
        print 'methodA'

    @staticmethod
    def methodB():
        print 'methodB'
        __class__.methodA()
Answered By: matt.baker
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.