Python
Class Methods and Static Methods in Python: Usages and Differences
Understanding the most confusing concepts of Python OOP
Introduction
When we define some methods in a Python class, we usually use instance methods. For example:
Summary
This text explains the differences between instance methods, class methods, and static methods in Python, along with their respective usages and examples.
Abstract
The text begins by introducing the concept of instance methods in Python, which have a mandatory first attribute called self representing the instance itself. It then moves on to explain class methods, which have a mandatory first attribute cls representing the class itself and can be called by an instance or the class directly. The most common usage of class methods is to define a factory method. Lastly, the text discusses static methods, which don't have any attributes of instances or the class and are commonly used to define helper or utility functions closely related to the class. The text concludes by summarizing the differences between instance methods, class methods, and static methods.
Opinions
When we define some methods in a Python class, we usually use instance methods. For example:
The method __init__ and set_nickname are instance methods, which first parameter is self. The self represents the current instance itself. However, in some scenario, only using instance methods is not enough. Therefore, Python has two build-in decorators called @classmethod and @staticmethod. This post will explain and compare these types of methods with simple examples.
A class method is a method which first parameter is the class itself. We use cls to represent this mandatory parameter.
As its name shown, class method can be called by the class directly and no need to instantiate an instance to call the method. In a nutshell, a class method can be called by class directly or by an instance but a instance method can only be called by an instance.
It’s very convenient to define a class method in Python classes. We can just add a build-in decorator @classmethod before the declaration of a method.
Let’s look an example:
As the above code shows, s2=Student.set_nickname('yang')causes a TypeError. Because set_nickname() is an instance method which doesn’t decorated by @classmethod. An instance method’s first parameter is the instance who calls it. Therefore, it must be called by an instance of the class rather than the class itself.
In the other hand, get_from_string is a class method whose first parameter is the class itself, so it can be invoked by class directly.
The mechanism of class method gives us abilities to add more functionalities to a class. The most common scenario of using class methods is to define a factory method. Factory Pattern is one of popular software design patterns.
In the class Student example, we defined a factory called get_from_string which can ‘produce’ a Student instance from a string input. We know the build-in __init__method is a constructor of a class, but if we need to create an instance by other ways, it’s hard to use an instance method as a factory to produce new instances, because when we use an instance method, we must have an instance at first.
Therefore, class method gives us ability to define factory methods. We can produce Student instances by any ways we like:
Static method is a method within a class that doesn’t have parameters of the class or instance. We can define a static method using build-in decorator @staticmethod.
As shown above, the suitable_age is a static method, it doesn’t have parameters like self or cls. It doesn’t matter whether we call a static method by class or instance.
Because static methods don’t contain parameters about a specific class or instances. We can totally define it as an independent function out of a class and use it as other normal functions out of classes.
Is the static method concept is unnecessary?
Not at all, the mechanism of static methods help us manage our classes and functions better. If we look some famous open-source Python projects, there are many static methods used as helper or utility methods within a class.
For our example, the suitable_age method checks whether a person’s age is suitable to be a student, and this logic is closely related to the Student class. There could be many functions and classes in one Python module, if we define the suitable_age function out of the Student class, it could be difficult to clearly see what this function is used for and what it is related to.
Therefore, a good object-oriented programming habit is:
Define a function as a static method within a class if this function’s logic is closely related to the class.
Let’s have a try:
It works well, but actually it’s not a good idea to define factory by static method. It could cause some unintended consequences. Look a more complex example:
As above shown, we create instances by NewStudent class which is inherited from Student class. However, we get two instances of Student class rather than NewStudent class. This is because our factory methods return Student class. For a class method, we can change it return statement a little and get a expected result:
The new_s1 is a instance of NewStudent class now, which is our expected result! But for the static method, we can’t make the same modification, because static method doesn’t have the parameter cls representing the class itself.
Therefore, it’s not a good idea to use static method to produce instances. It’s not as flexible and powerful as class method when used as a factory. And could cause unexpected result, such as getting a instance of Student class when creating a instance using NewStudent class.
Let’s look an example using all the different types of methods:
self which represent the instance itself. Instance method must be called by a instantiated instance.cls which represent the class itself. Class method can be called by an instance or by the class directly. Its most common using scenario is to define a factory method.Thanks for reading. ❤️
Join Medium through my referral link to access millions of great articles:
Mohammed ZeroualWhen working with Python’s class hierarchy, understanding Method Resolution Order (MRO) is essential, particularly in the context of…
Kiran MaanPython developers don’t do this…instead use this way!!
Sabrina Carpenter 🐍I’ve spent years optimizing workflows for code. Python’s simplicity and versatility make it my go-to tool for solving everyday problems…
Sarowar Jahan SauravData science is a multidisciplinary field that combines mathematics, statistics, computer science, and domain expertise to extract insights…