Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python classmethod()
1
Python classmethod()

Python’s built-in function
Code:
classmethod()
prefixes a method definition in a class as an annotation
Code:
@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

Code:
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:

Code:
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
    Code:
    C.f(arg1, arg2, ...)
    , or

  • You can call it on an instance such as
    Code:
    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
Code:
C.f(arg1, arg2, ...)
, Python really runs
Code:
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
Code:
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
Code:
Coffee(80, 20, 'Arrabica')
, a user can just call
Code:
cappuccino()
to create the same instance of the class
Code:
Coffee
. This simplifies the creation of new instances and can improve the readability and usability of your code:

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:

Code:
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

[Image: image-47-1024x704.png]Click to run code (interactive Jupyter Notebook)

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
Code:
cls
—short for “class”, but we cannot take this because
Code:
class
is a reserved keyword. You can use any name you want but using the name
Code:
cls
is the expected convention and it’s highly recommended. The naming convention of the first implicit argument of instance methods is the name
Code:
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
Code:
@classmethod
is a function decorator. It’s short for calling
Code:
classmethod(m)
for the method
Code:
m
that you would decorate.

Here’s the same simplified coffee example without using a decorator and by using classmethod() instead:

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}' def cappuccino(cls): return cls(80, 'Arrabica') Coffee.cappuccino = classmethod(Coffee.cappuccino) print(Coffee.cappuccino())

The output is the same:

Code:
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
Code:
@classmethod
annotator, you obtain an instance method per default. The instance method requires that the first argument
Code:
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
Code:
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:

Code:
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
    Code:
    C.f(arg1, arg2, ...)
    , or

  • You can call it on an instance such as
    Code:
    C().f(arg1, arg2, ...)
    .

But there’s only one way of using an instance method:
  • You can call it on an instance such as
    Code:
    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
Code:
@staticmethod
annotation rather than the
Code:
@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:

Code:
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
Code:
classmethod()
prefixes a method definition in a class as an annotation
Code:
@classmethod
.

Code:
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:

Code:
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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

The post Python classmethod() first appeared on Finxter.
Reply

Users browsing this thread:
1 Guest(s)

Forum Jump: