chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Python instance method vs. Static method vs. Class method

2017-05-09

In Python, there are three methods:

  • Instance method
  • Static method
  • Class method

Look at the following code, have a test for yourself, what are the output:

[gist 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

Reference:

Stackoverflow

arkilis

Comments: