A class method in Python is a method that is bound to the class rather than the object (instance). It can access and modify class-level data (class variables) but not instance-specific data directly.
Class methods are defined using the @classmethod decorator.
A class method is a method that:
cls (class reference) as its first parameterclass ClassName:
@classmethod
def method_name(cls):
# code
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print("School:", cls.school)
Student.show_school()
Output
School: ABC School
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print(cls.school)
s1 = Student()
s1.show_school()
self vs cls| Feature | Instance Method | Class Method |
|---|---|---|
| First parameter | self |
cls |
| Access | Instance variables | Class variables |
| Called by | Object | Class or Object |
class Student:
school = "ABC School"
@classmethod
def change_school(cls, new_name):
cls.school = new_name
Student.change_school("XYZ School")
print(Student.school)
Output
XYZ School
Class methods are often used to create alternative constructors.
class Student:
def __init__(self, name):
self.name = name
@classmethod
def from_string(cls, data):
name = data.split("-")[0]
return cls(name)
s1 = Student.from_string("Rahul-20")
print(s1.name)
Use class methods when:
@classmethod decoratorclscls to refer to the class.@classmethod decorator.