Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call static methods inside the same class in python

Tags:

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.

like image 616
Haoliang Yu Avatar asked Feb 17 '16 14:02

Haoliang Yu


People also ask

How do you call a static method in the same class Python?

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.

How do you call a static method in the same class?

Qualifying a static call setText(""); A static method is called by prefixing it with a class name, eg, Math.

How do you call a method in the same class Python?

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.

Can I call a static method inside a regular one?

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.


2 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() 
like image 77
Ismael Infante Avatar answered Sep 30 '22 10:09

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() 
like image 20
Jing He Avatar answered Sep 30 '22 08:09

Jing He