Class Methods in Python – @classmethod, Syntax & Examples

Introduction

Python supports Object-Oriented Programming (OOP), which allows developers to organize code using classes and objects. Within a class, Python provides three main types of methods:

  1. Instance Methods
  2. Class Methods
  3. Static Methods

Among these, Class Methods are used when you need to work with class-level data rather than object-specific data.

Class methods are defined using the @classmethod decorator and receive the class as the first parameter, conventionally named cls.

For example, if all students belong to the same school, the school name can be stored as a class variable. A class method can then be used to update the school name for all students at once.

What is a Class Method in Python?

A class method is a method that belongs to the class rather than an individual object.

It receives the class itself as its first argument using:


cls

instead of:


self

Class methods are created using the @classmethod decorator.

Example:


class Student:
    school = "ABC School"
    @classmethod
    def show_school(cls):
        print(cls.school)

Usage:


Student.show_school()

Output:

ABC School

Explanation:

The method accesses the class variable without creating an object.

Syntax

Basic syntax:


class ClassName:
    @classmethod
    def method_name(cls):
        # code

Where:

  • @classmethod converts the method into a class method.
  • cls refers to the class itself.

Creating a Simple Class Method

Example:


class Student:
    school = "ABC School"
    @classmethod
    def display_school(cls):
        print(cls.school)
Student.display_school()

Output:

ABC School

Explanation:

The method accesses the class variable using cls.

Understanding cls

In instance methods, self refers to the current object.

In class methods, cls refers to the class itself.

Example:


class Student:
    @classmethod
    def show_class(cls):
        print(cls)

Usage:


Student.show_class()

Output:

<class ‘__main__.Student’>

The cls parameter represents the class object.

Accessing Class Variables

Class methods are commonly used to access class variables.

Example:


class Employee:
    company = "Tech Solutions"
    @classmethod
    def show_company(cls):
        print(cls.company)
Employee.show_company()

Output:

Tech Solutions

Modifying Class Variables

Class methods can also modify class-level data.

Example:


class Employee:
    company = "Tech Solutions"
    @classmethod
    def change_company(cls, name):
        cls.company = name

Usage:


Employee.change_company("ABC Technologies")
print(Employee.company)

Output:

ABC Technologies

The change affects all objects of the class.

Class Methods and Objects

Class methods can be called using objects as well.

Example:


class Student:
    school = "ABC School"
    @classmethod
    def show_school(cls):
        print(cls.school)
student = Student()
student.show_school()

Output:

ABC School

However, calling class methods using the class name is generally preferred.

Alternative Constructors Using Class Methods

One of the most powerful uses of class methods is creating alternative constructors.

Example:


class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @classmethod
    def from_string(cls, data):
        name, age = data.split(",")
        return cls(name, int(age))

Usage:


student = Student.from_string(
    "John,20"
)
print(student.name)
print(student.age)

Output:

John 20

Explanation:

The class method creates an object from a string.

Real-Life Examples:

1. Employee System


class Employee:
    company = "XYZ Pvt Ltd"
    def __init__(self, name):
        self.name = name
    @classmethod
    def change_company(cls, company):
        cls.company = company

Usage:


emp1 = Employee("John")
emp2 = Employee("Mike")
Employee.change_company(
    "ABC Technologies"
)
print(emp1.company)
print(emp2.company)

Output:

ABC Technologies
ABC Technologies

The company name changes for all employees.

2. Bank System


class Bank:
    interest_rate = 5
    @classmethod
    def update_interest_rate(
        cls,
        rate
    ):
        cls.interest_rate = rate

Usage:


Bank.update_interest_rate(7)
print(Bank.interest_rate)

Output:

7

The interest rate applies to all accounts.

3. Product Factory


class Product:
    def __init__(
        self,
        name,
        price
    ):
        self.name = name
        self.price = price
    @classmethod
    def from_dict(
        cls,
        data
    ):
        return cls(
            data["name"],
            data["price"]
        )

Usage:


product_data = {
    "name": "Laptop",
    "price": 50000
}
product = Product.from_dict(
    product_data
)
print(product.name)

Output:

Laptop

This is a practical factory method implementation.

Class Methods vs Instance Methods

Feature Class Method Instance Method
First Parameter cls self
Access Class Variables Yes Yes
Access Instance Variables No Yes
Requires Object No Yes
Decorator @classmethod None

Instance Method Example


class Student:
    def __init__(self, name):
        self.name = name
    def display(self):
        print(self.name)

Instance methods work with object data.

Class Methods vs Static Methods

Feature Class Method Static Method
Uses cls Yes No
Uses self No No
Access Class Variables Yes Indirectly
Decorator @classmethod @staticmethod
Purpose Class Operations Utility Functions

Example: Class Method vs Static Method


class Student:
    school = "ABC School"
    @classmethod
    def show_school(cls):
        print(cls.school)
    @staticmethod
    def welcome():
        print("Welcome")

Usage:


Student.show_school()
Student.welcome()

Output:

ABC School Welcome

Factory Methods Using Class Methods

Factory methods create objects in different ways.

Example:


class User:
    def __init__(
        self,
        username
    ):
        self.username = username
    @classmethod
    def guest_user(cls):
        return cls("Guest")

Usage:


user = User.guest_user()
print(user.username)

Output:

Guest

Factory methods simplify object creation.

Advantages of Class Methods

Advantage Description
Access Class Data Direct access to class variables
Alternative Constructors Multiple ways to create objects
Better Organization Keeps class logic together
Shared Data Management Modify common values easily
Reusability Avoid duplicate code

Disadvantages of Class Methods

Disadvantage Description
Cannot Access Instance Data Directly No self parameter
Limited Scope Works mainly with class-level data
Can Be Misused Not suitable for object-specific operations

Common Mistakes

1. Using self Instead of cls

Incorrect:


@classmethod
def show(self):
    pass

Correct:


@classmethod
def show(cls):
    pass

2. Forgetting @classmethod

Incorrect:


def show(cls):
    pass

Without the decorator, it becomes a regular instance method.

3. Accessing Instance Variables

Incorrect:


@classmethod
def show(cls):
    print(cls.name)

If name is an instance variable, this will fail.

4. Using Class Methods for Object-Specific Data

Wrong use case:


@classmethod
def display_name(cls):

Object-specific information should use instance methods.

5. Overusing Class Methods

Not every method should be a class method.

Choose the appropriate method type based on the requirement.

Conclusion

Class methods are an important feature of Python’s Object-Oriented Programming model. They allow developers to work with class-level data, modify shared variables, and create alternative constructors using the @classmethod decorator.

Class methods operate on the class itself through the cls parameter. They are widely used in factory methods, configuration management, object creation, and shared data handling.

Related Python Tutorials