I can't find if it's possible to call a non-static method from a static one in Python.
Thanks
EDIT: Ok. And what about static from static? Can I do this:
class MyClass(object):
@staticmethod
def static_method_one(cmd):
...
@staticmethod
def static_method_two(cmd):
static_method_one(cmd)
It's perfectly possible, but not very meaningful. Ponder the following class:
Obviously, we can call this in the expected ways:
But also consider this:
The syntax
instance.normal_method()
is pretty much just a "shortcut" forMyClass.normal_method(instance)
. That's why there is this "self" parameter in methods, to pass in self. The name self is not magical, you can call it whatever you want.The same trick is perfectly possible from withing a static method. You can call the normal method with an instance as first parameter, like so:
So the answer is yes, you can cal non-static methods from static methods. But only if you can pass in an instance as first parameter. So you either have to generate it from inside the static method (and in that case you are probably better off with a class method) or pass it in. But if you pass in the instance, you can typically just make it a normal method.
So you can, but, it's pretty pointless.
And that then begs the question: Why do you want to?
It's not possible withotut the instance of the class. You could add a param to your method
f(x, y, ..., me)
and useme
as the object to call the non-static methods on.When in a static method, you don't have a self instance: what object are you calling the non-static methods on? Certainly if you have an instance lying around, you can call methods on it.
Use class methods, not static methods. Why else put it inside a class?
After the other answers and your follow-up question - regarding static method from static method: Yes you can:
And, in case you're curious, also yes for class method from class method (easy to test this stuff in the interpreter - all this is cut and pasted from Idle in 2.5.2)
[**EDITED to make correction in usage pointed out by others**]
: