Understand Python @classmethod and @staticmethod with Examples: A Beginner Guide – Python Tutorial

By | December 25, 2019

When you are learning python class programming, you may find two kinds of class methods:@classmethod and @staticmethod. In this tutorial, we will use some examples to show you how to understand and use them correctly.

What are python @classmethod and @staticmethod methods?

In order to use them correctly, you should remmenber:

  • These two kinds of methods are often used to manage python class variables.
  • We can call these methods by class name

To understand python clas variables, you can read this tutorial.

Understand Python Class Variables with Examples: A Beginner Guide – Python Tutorial

We will use a template code to explain.

Here is an example code.

class Test:
    count = 0
    def __init__(self):
        print("init a class variable")
        
    def add(self):
        Test.count += 1
        print("class variable count is = " + str(Test.count))
    @classmethod
    def addx(cls):
        Test.count += 1
        print("add count with class method, count is = " + str(Test.count))
    @staticmethod    
    def add_static():
        Test.count += 10
        print("add count with static method, count is = " + str(Test.count))

In this python class Test, we have create a @classmethod and @staticmethod methods.

Differences between @classmethod and @staticmethod methods

There are two main differences:

1. @classmethod method has a parameter cls. However, @staticmethod does not.

for example:

def addx(cls):
    pass

2.@classmethod method can call python class variables by cls.class_variable_name. However, @staticmethod method only be allowed class_name.class_variable_name

For example, in addx() function.

def addx(cls):
        Test.count += 1
        # or cls.count += 1

How to use python @classmethod and @staticmethod methods?

First, we will use a Test instance to call methods.

t1 = Test()
t1.add()
t1.addx()
t1.add_static()

Run this code, you will get result:

init a class variable
class variable count is = 1
add count with class method, count is = 2
add count with static method, count is = 12

From the result we can find: Python @classmethod and @staticmethod methods can be called by class instances.

Meanwhile, look at example below:

Test.addx()
Test.add_static()

Run this python script, we can get result:

add count with class method, count is = 13
add count with static method, count is = 23

From the result we can find: we can call python @classmethod and @staticmethod methods by class name.

Leave a Reply