Python Instance, Class, and Static Methods

created:

updated:

tags: python

When I first encountered Python’s instance, class, and static methods, I was quite confused. While I was implementing class methods for work, I looked up their definitions and examples.

Example Code

class MyClass:
    def method(self):
        return 'instance method called', self

    @classmethod
    def classmethod(cls):
        return 'class method called', cls

    @staticmethod
    def staticmethod():
        return 'static method called'

Instance Methods

From the above example, the method is the regular instance method. It takes one parameter, self which refers to an instance of MyClass. With self, instance methods can access attributes and other methods of the same instance of MyClass. In addition, instance methods can access and modify the instance’s state but also access class itself through self.__class__ attribute.

When calling instance methods, Python internally replaces self argument with the instance object.

Class Methods

We can mark class methods with the decorator @classmethod. Class methods receive cls parameter (instead of self) which refers to the class. Classmethods cannot modify object instance’s states. Instead, it can modify class states that apply to all instances of the class.

Static Methods

Static methods are marked with @staticmethod decorator. Static methods neither take self nor cls parameter. Static methods cannot modify object state or class state.

Calling Instance, Class, and Static methods

>>> obj = Myclass()
>>> obj.method()
# ('instance method called', <MyClass instance at 0x10205d190>)
>>> obj.classmethod()
# ('class method called', <class MyClass at 0x101a2f4c8>)
>>> obj.staticmethod()
# 'static method called'

>>> MyClass.method()
# TypeError: unbound method method() must
#    be called with MyClass instance as first
#    argument (got nothing instead)
>>> MyClass.classmethod()
# ('class method called', <class MyClass at 0x101a2f4c8>)
>>> MyClass.staticmethod()
# 'static method called'

Class methods and static methods can be called on either object or class, but instance method raises a TypeError.

References