In a python class, there are three kinds of methods:
- Instance method
- Static method
- Class method
Example explained
Look at the following code, have a test for yourself, what are the output:
class Foo(object):
variable = 1
def method(self, param):
print "run instance method (%s,%s)" % (self, param)
@classmethod
def class_method1(cls, param):
print "run class method (%s,%s)" % (cls, param)
@classmethod
def class_method2(cls):
print cls.variable
@staticmethod
def static_method1(param):
print "run static method (%s)" % param
@staticmethod
def static_method2():
print variable
foo = Foo()
foo.method("instance method")
#Foo.method("instance method again")
foo.class_method1("class method 1")
foo.class_method2()
Foo.class_method1("class method 1 again")
Foo.class_method2()
foo.static_method1("static method 1")
foo.static_method2()
Foo.static_method1("static method 1 again")
Foo.static_method2()
https://gist.github.com/arkilis/341bf667a577b04b8b3a58bce78809a6
Results:
1: foo.method("instance method") — OK
2: Foo.method("instance method again")
is wrong, as method
is the instance method. To run an instance method, you have to use a class instance
3: foo.class_method1("class method 1")
outputs run class method (<class '__main__.Foo'>,class method 1)
4: foo.class_method2()
outputs 1
5: Foo.class_method1("class method 1 again")
outpus run class method (<class '__main__.Foo'>,class method 1 again)
6: Foo.class_method2()
outputs 1
7: foo.static_method1("static method 1")
outputs run static method (static method 1)
8: foo.static_method2()
is wrong, as static_method2
is static method, which cannot access the instance level variable
9: Foo.static_method1("static method 1 again")
outputs run static method (static method 1 again)
10: Foo.static_method2()
is wrong, which cannot access the class level variable
Conclusion
- instance method (i.e.
method()
) must be called by a class instance - class method can be called either by a class instance or class itself
- static method is quite special in Python, as it is also can be called by a class instance or class itself
- the only difference between a static method and a class method, class method can access the class’s variable that static can’t