Python Class' Instance method, Class method, and Static Methods Demystified
Let’s begin by writing a (Python 3, no need for inheriting "object", see?) class that contains simple examples for all three method types:
NOTE: For Python 2 users: The
@staticmethod
and@classmethod
decorators are available as of Python 2.4 and this example will work as is. Instead of using a plainclass MyClass:
declaration you might choose to declare a new-style class inheriting fromobject
with theclass MyClass(object)
Instance Methods -- accesses to object state and class state
The first method on MyClass
, called method
, is a regular instance method. That’s the basic, no-frills method type you’ll use most of the time. You can see the method takes one parameter, self
, which points to an instance of MyClass
when the method is called (but of course instance methods can accept more than just one parameter).
Through the self
parameter, instance methods can freely access attributes and other methods on the same object. This gives them a lot of power when it comes to modifying an object’s state.
Not only can they modify object state, instance methods can also access the class itself through the self.__class__
attribute. This means instance methods can also modify class state.
Class Methods -- only have access to class state
Let’s compare that to the second method, MyClass.classmethod
. I marked this method with a @classmethod
decorator to flag it as a class method.
Instead of accepting a self
parameter, class methods take a cls
parameter that points to the class—and not the object instance—when the method is called.
Because the class method only has access to this cls
argument, it can’t modify object instance state. That would require access to self
. However, class methods can still modify class state that applies across all instances of the class.
Static Methods -- no accesses to either state
The third method, MyClass.staticmethod
was marked with a @staticmethod
decorator to flag it as a static method.
This type of method takes neither a self
nor a cls
parameter (but of course it’s free to accept an arbitrary number of other parameters).
Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access - and they’re primarily a way to namespace your methods.
Last updated