classmethod() in Python

A class method receives the class itself as its first argument (conventionally named cls). This allows us to call the method on the class without first creating an instance. We use the @classmethod decorator before the method declaration to define a class method.

Key Features of Class Methods

  • A classmethod is bound to a class and does not depend on the instantiation of a class to be used.

  • A classmethod can modify class attributes which propagate to all instances of the class.

  • The first parameter is always the class itself (by convention named cls).

Using the @classmethod Decorator

In the example below, we create a class called WeekDay and define a class method daynames. We can access this method directly on the class without creating an instance ?

class WeekDay:
    day_name = ['Mon','Tue','Wed','Thu','Fri']
    
    @classmethod
    def daynames(cls):
        print('The WeekDays are', cls.day_name)

# Call on class directly
WeekDay.daynames()

# Call on instance (also works)
WeekDay().daynames()
The WeekDays are ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The WeekDays are ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Class Method vs Regular Function

To show why class methods are useful, here's how we would achieve similar functionality without using a class method ?

def daynames():
    day_name = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
    print('The WeekDays are', day_name)

daynames()
The WeekDays are ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Practical Example: Alternative Constructor

Class methods are commonly used as alternative constructors ?

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @classmethod
    def from_string(cls, person_str):
        name, age = person_str.split('-')
        return cls(name, int(age))
    
    def __str__(self):
        return f"{self.name} is {self.age} years old"

# Regular constructor
person1 = Person("Alice", 25)
print(person1)

# Using class method as alternative constructor
person2 = Person.from_string("Bob-30")
print(person2)
Alice is 25 years old
Bob is 30 years old

Conclusion

Class methods provide a way to call methods on a class without instantiation and are commonly used for alternative constructors. They receive the class as the first parameter and can modify class-level attributes that affect all instances.

Updated on: 2026-03-15T19:11:59+05:30

517 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements