Introduction
In Python, a class method is a method that operates on the class itself rather than on an instance of the class. Class methods are defined using the @classmethod decorator and take cls as their first parameter, which represents the class. Therefore, they can be used to modify class attributes. Additionally, they allow the creation of alternative constructors and help in implementing factory methods, making object creation more flexible.
Defining a Class Method
To define a class method, use the @classmethod decorator and include cls as the first parameter.
Syntax:
class ClassName:
class_attribute = "Shared Attribute"
@classmethod
def class_method_name(cls, parameters):
# Method logicExample:
class Employee:
company = "TechCorp"
@classmethod
def change_company(cls, new_name):
cls.company = new_name # Modifies the class attribute
# Before changing the company name
print(Employee.company) # Output: TechCorp
# Using the class method
Employee.change_company("InnovateX")
# After changing the company name
print(Employee.company) # Output: InnovateXIn this example, the change_company method modifies the class attribute company for all instances.
Key Features of Class Methods in Python
They work on the class level rather than the instance level.
Can modify class attributes shared across all instances.
They allow alternative constructors to create instances in a different way.
Do not require an instance to be called; they can be accessed via the class itself.
Class Methods vs. Instance Methods vs. Static Methods

Using Class Methods as Alternative Constructors
Python Class methods can be used to create alternative constructors. This is useful when you need multiple ways to instantiate a class.
Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, student_info):
name, age = student_info.split("-")
return cls(name, int(age))
# Creating an object using the alternative constructor
student = Student.from_string("Alice-21")
print(student.name, student.age) # Output: Alice 21Here, from_string provides an alternative way to create a Student object using a formatted string.
When to Use Python Class Methods?
- When modifying or accessing class attributes.
- defines alternative constructors.
- performs operations that do not rely on instance-specific data.
Conclusion
Python Class methods are powerful tools in Python’s OOP paradigm. They allow you to interact with the class itself, modify class attributes, and create alternative ways to instantiate objects. By using @classmethod, you can ensure that a method works across all instances without needing an object to call it.