Python’s built-in function
prefixes a method definition in a class as an annotation classmethod
()@classmethod
. This annotation transforms a normal instance method into a class method. The difference between class and instance method is that Python passes the class itself as a first implicit argument of the method rather than the instance on which it is called.
In this tutorial, I’ll show you one of Python’s little-known secrets that separate the intermediates from the experts: class methods. You may know the difference between an instance method and a class method conceptually. (If you don’t, this tutorial is for you.) But do you also know how to create a class method in Python? If not, read on, because this tutorial will show you!
Syntax Class Method
Syntax:classmethod(function)
# <--- This is considered unpythonic@classmethod
# <--- As a prefix before the used method
The most Pythonic way to declare a class method is the following decorator syntax:
class C: @classmethod def f(cls, arg1, arg2, ...): None
How to Call a Class Method?
There are two ways of using a class method:
- You can call it on a class such as
C.f(arg1, arg2, ...)
, or - You can call it on an instance such as
C().f(arg1, arg2, ...)
.
Note that Python implicitly passes the class itself—in Python, everything including a class is an object—as a first argument. Roughly speaking, if you call C.f(arg1, arg2, ...)
, Python really runs f(C, arg1, arg2, ...)
with the class object passed as a first argument.
Example Class Method
When to use a class method? You’ll find that class methods are often used in a factory pattern. A factory pattern is one of the most popular software development patterns: a so-called factory method creates new instances of a certain type. It is responsible for actually creating the instances from a given class definition.
In the following example, you define a class Coffee
that represents a real coffee serving in a coffee bar. There are many specialities such as Cappuccino (80% milk, 20% coffee), Espresso Macchiato (30% milk, 70% coffee), and Latte Macchiato (95% milk, 5% coffee).
You use the class methods to allow users to conveniently call factory methods instead of setting the milk level themselves. Instead of calling Coffee(80, 20, 'Arrabica')
, a user can just call cappuccino()
to create the same instance of the class Coffee
. This simplifies the creation of new instances and can improve the readability and usability of your code:
class Coffee: def __init__(self, milk, beans): self.milk = milk # percentage self.coffee = 100-milk # percentage self.beans = beans def __repr__(self): return f'Milk={self.milk}% Coffee={self.coffee}% Beans={self.beans}' @classmethod def cappuccino(cls): return clf(80, 'Arrabica') @classmethod def espresso_macchiato(cls): return cls(30, 'Robusta') @classmethod def latte(cls): return cls(95, 'Arrabica') print(Coffee.cappuccino()) print(Coffee.espresso_macchiato()) print(Coffee.latte())
The three lines of output are:
Milk=80% Coffee=20% Beans=Arrabica Milk=30% Coffee=70% Beans=Robusta Milk=95% Coffee=5% Beans=Arrabica
You can run this example in our interactive Jupyter Notebook:
Interactive Example Class Method
Exercise: Can you create another coffee specialty?
Class Method Naming Convention: cls vs self
In the previous example, you’ve seen the naming convention of the first argument of a class method: it’s the three characters cls
—short for “class”, but we cannot take this because class
is a reserved keyword. You can use any name you want but using the name cls
is the expected convention and it’s highly recommended. The naming convention of the first implicit argument of instance methods is the name self
.
Related Article: Self in Python
Class Method is a Function Decorator
Decorators help to add functionality to existing code without having to modify the code itself. Decorators are so-called because they decorate code, they do not modify the code, but they make the code do different things using decoration. Now that we have understood closures, we can work our way step by step to understanding and using decorators.
The @classmethod
is a function decorator. It’s short for calling classmethod(m)
for the method m
that you would decorate.
Here’s the same simplified coffee example without using a decorator and by using classmethod() instead:
class Coffee: def __init__(self, milk, beans): self.milk = milk # percentage self.coffee = 100-milk # percentage self.beans = beans def __repr__(self): return f'Milk={self.milk}% Coffee={self.coffee}% Beans={self.beans}' def cappuccino(cls): return cls(80, 'Arrabica') Coffee.cappuccino = classmethod(Coffee.cappuccino) print(Coffee.cappuccino())
The output is the same:
Milk=80% Coffee=20% Beans=Arrabica
However, this is not the recommended way—use a decorator with the @ annotation instead!
Related Article: Decorators
Class Method vs Instance Method
If you don’t use the @classmethod
annotator, you obtain an instance method per default. The instance method requires that the first argument self
is a reference to the instance itself on which the method is called. The class method expects a reference to the class, not the instance, as a first argument cls
. Thus, the difference between class and instance methods is that Python passes the class rather than the instance (object) as a first implicit argument.
Here’s a minimal example of a class and an instance method:
class C: @classmethod def f(cls): None # instance method def g(self): None # call class method: C.f() # call instance method: C().g()
There are two ways of using a class method:
- You can call it on a class such as
C.f(arg1, arg2, ...)
, or - You can call it on an instance such as
C().f(arg1, arg2, ...)
.
But there’s only one way of using an instance method:
- You can call it on an instance such as
C().g()
.
Class Method vs Static Method
You may know static methods from programming languages such as C++ or Java. They’re methods that exist independently of whether or not you created an instance of the class. That’s why they don’t use any instance variable in the method body. If you want to use a static method in Python, you need to use the @staticmethod
annotation rather than the @classmethod
annotation. The difference is that static methods don’t expect a reference to either the instance or the class as an implied first argument.
Here’s an example comparing class methods, instance methods, and static methods:
class C: @classmethod def f(cls): None # instance method def g(self): None @staticmethod def h(): None # call class method: C.f() # call instance method: C().g() # call static method: C.h()
Summary
Python’s built-in function
prefixes a method definition in a class as an annotation classmethod
()@classmethod
.
class C: @classmethod def f(cls, arg1, arg2, ...): None
This annotation transforms a normal instance method into a class method.
The difference between class and instance method is that Python passes the class itself as a first implicit argument of the method rather than the instance on which it is called:
class C: @classmethod def f(cls, arg1, arg2, ...): None # instance method def g(self, arg1, arg2, ...): None
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.