From a famous example, I learned the difference between method, classmethod and staticmethod in a Python class.
Source:
What is the difference between @staticmethod and @classmethod in Python?
class A(object):
def foo(self,x):
print "executing foo(%s,%s)"%(self,x)
@classmethod
def class_foo(cls,x):
print "executing class_foo(%s,%s)"%(cls,x)
@staticmethod
def static_foo(x):
print "executing static_foo(%s)"%x
# My Guesses
def My_Question(self,x):
self.foo(x)
A.class_foo(x)
A.static_foo(x)
a=A()
Now I am wondering, how to call a method, @classmethod
, and @staticmethod
inside the class.
I put my guesses in the My_Question
function above, please correct me if I am wrong with any of these.
Best Answer
Yes, your guesses will work. Note that it is also possible/normal to call staticmethods and classmethods outside the class:
Also note that inside regular instance methods, it's customary to call the staticmethods and class methods directly on the instance (
self
) rather than the class (A
):This allow for inheritance to work as you might expect -- If I create a
B
subclass fromA
, if I callB.instance_method()
, myclass_foo
function will getB
instead ofA
as thecls
argument -- And possibly, if I overridestatic_foo
onB
to do something slightly different thanA.static_foo
, this will allow the overridden version to be called as well.Some examples might make this more clear:
...
After you've run that, try it by changing all of the
self.
toA.
insideinstance_method
. Rerun and compare. You'll see that all of the references toB
have gone (even when you're callingb.instance_method()
). This is why you want to useself
rather than the class.