class methods and instance methods
amitmund
June 04, 2026
12. Class Methods
What is a Class Method?
A class method is a method that works with the class itself rather than with individual objects.
Class methods are created using the @classmethod decorator.
Example
class Student:
school = "ABC School"
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
Output
ABC School
What is a Class Variable?
school = "ABC School"
This is a class variable.
It belongs to the class itself.
Student.school
Output:
ABC School
Understanding cls
In a class method:
@classmethod
def get_school(cls):
cls refers to the class.
Python internally does something similar to:
Student.get_school(Student)
Therefore:
cls = Student
Understanding cls.school
Since:
cls = Student
Then:
cls.school
becomes:
Student.school
Output:
ABC School
Visual Representation
Student Class
│
├── school = "ABC School"
│
└── get_school()
Calling:
Student.get_school()
makes:
cls
│
▼
Student Class
Therefore:
cls.school
accesses:
Student.school
Difference Between self and cls
| self | cls |
|---|---|
| Refers to an object | Refers to a class |
| Used in instance methods | Used in class methods |
| Receives the current object | Receives the current class |
Example:
def show(self):
@classmethod
def get_school(cls):
Why Use Class Methods?
Class methods are useful when working with class variables.
Example:
class Student:
school = "ABC School"
@classmethod
def change_school(cls, new_name):
cls.school = new_name
Usage:
Student.change_school("XYZ School")
Now:
print(Student.school)
Output:
XYZ School
Real-Life Analogy
Imagine:
School
│
├── Name = ABC School
│
├── Student 1
├── Student 2
└── Student 3
The school name belongs to the school, not to any particular student.
A class method works with information that belongs to the class itself.
Rule to Remember
- Use
selfwhen working with object data. - Use
clswhen working with class data. - Class methods are created using
@classmethod. - Class methods can access and modify class variables.