Static methods - How to call a method from another method?
When I have regular methods for calling another method in a class, I have to do this
class test:
def __init__(self):
pass
def dosomething(self):
print "do something"
self.dosomethingelse()
def dosomethingelse(self):
print "do something else"
but when I have static methods I can't write
self.dosomethingelse()
because there is no instance. What do I have to do in Python for calling an static method from another static method of the same class?
Solution 1:
How do I have to do in Python for calling an static method from another static method of the same class?
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_method(cls) :
cls.static_method_to_call()
Solution 2:
class.method
should work.
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
Solution 3:
NOTE - it looks like the question has changed some. The answer to the question of how you call an instance method from a static method is that you can't without passing an instance in as an argument or instantiating that instance inside the static method.
What follows is mostly to answer "how do you call a static method from another static method":
Bear in mind that there is a difference between static methods and class methods in Python. A static method takes no implicit first argument, while a class method takes the class as the implicit first argument (usually cls
by convention). With that in mind, here's how you would do that:
If it's a static method:
test.dosomethingelse()
If it's a class method:
cls.dosomethingelse()
Solution 4:
OK the main difference between class methods and static methods is:
- class method has its own identity, that's why they have to be called from within an INSTANCE.
- on the other hand static method can be shared between multiple instances so that it must be called from within THE CLASS