avatarYang Zhou

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

  • The text emphasizes the importance of class methods in defining factory methods, which are useful in creating instances of a class in various ways.
  • The text suggests that static methods are useful in managing classes and functions better by defining helper or utility functions within a class, which are closely related to the class.
  • The text advises against using static methods as a factory, as it could cause unexpected results and is not as flexible or powerful as class methods.
  • The text concludes by summarizing the key differences between instance methods, class methods, and static methods, emphasizing their respective usages and advantages.

Python

Class Methods and Static Methods in Python: Usages and Differences

Understanding the most confusing concepts of Python OOP

Photo by Christopher Czermak on Unsplash

Introduction

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.

Class Method

What is Class Method ?

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.

Why use class method ?

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.

Photo by Science in HD on Unsplash

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

What is Static Method ?

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.

Why Use Static Method ?

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.

Can Static Method Be A Factory?

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.

A Full Example

Let’s look an example using all the different types of methods:

Conclusion

  1. Instance method has a mandatory first attribute self which represent the instance itself. Instance method must be called by a instantiated instance.
  2. Class method has a mandatory first attribute 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.
  3. Static method doesn’t have any attributes of instances or the class. It also can be called by an instance or by the class directly. Its most common using scenario is to define some helper or utility functions which are closely relative to the class.

Thanks for reading. ❤️

Join Medium through my referral link to access millions of great articles:

Programming
Python
Object Oriented
Recommended from ReadMedium