30

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.

3 Answers 3

33

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()
Sign up to request clarification or add additional context in comments.

Comments

9

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

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

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

2 Comments

What is the difference/benefit of this vs. using @staticmethod and using the name of the class?
@JamesCarter if you use classmeethod, you get the cls variable, which refers to the containing class itself, so you can use this "cls" to refer to the class and its resources (method, attribute). If you use staticmethod, you can only use the class name to refer to the class, and if you are in a child class and inherit static method from parent class, the class name in the static method still remains the parent class name...
1
class A:
    @staticmethod
    def methodA():
        print 'methodA'

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

1 Comment

+1 for a handy solution because explicitly naming a class when calling a static method within it isn't nice :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.