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.

asked Feb 17, 2016 at 14:25

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()
answered Feb 17, 2016 at 14:36
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()
costaparas
5,24711 gold badges20 silver badges28 bronze badges
answered Nov 23, 2019 at 9:19

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()
answered May 9, 2022 at 10:15

1 Comment

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.