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
Haoliang Yu
3,0978 gold badges26 silver badges28 bronze badges
3 Answers 3
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
Ismael Infante
5324 silver badges8 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Jing He
9241 gold badge11 silver badges19 bronze badges
2 Comments
James Carter
What is the difference/benefit of this vs. using @staticmethod and using the name of the class?
Jing He
@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...
class A:
@staticmethod
def methodA():
print 'methodA'
@staticmethod
def methodB():
print 'methodB'
__class__.methodA()
answered May 9, 2022 at 10:15
matt.baker
2562 silver badges12 bronze badges
1 Comment
AntonK
+1 for a handy solution because explicitly naming a class when calling a static method within it isn't nice :)
lang-py