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.
A static method doesn't have access to the class and instance variables because it does not receive an implicit first argument like self and cls . Therefore it cannot modify the state of the object or class. The class method can be called using ClassName. method_name() as well as by using an object of the class.
Qualifying a static call setText(""); A static method is called by prefixing it with a class name, eg, Math.
To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self.
A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.
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()
As @Ismael Infante says, you can use the @classmethod
decorator.
class A: @staticmethod def methodA(): print 'methodA' @classmethod def methodB(cls): cls.methodA()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With