The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
In Python, class methods are special methods that are
bound to the class (not the instance). They can modify or access class-level data shared across all instances.
class Student:
school_name = "Green Valley High"
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def change_school(cls, new_name):
cls.school_name = new_name
# Before changing
print(Student.school_name) # Green Valley High
# Change using class method
Student.change_school("Blue Ridge Academy")
print(Student.school_name) # Blue Ridge Academy
Explanation:
change_school() is called on the class, not on an instance.
It modifies the class variable, and the change affects
all instances.
4. Difference Between Instance, Class, and Static Methods
Method Type
Decorator
First Parameter
Can Access Instance (self)
Can Access Class (cls)
Common Use
Instance Method
(None)
self
Yes
Via self.__class__
Works on instance data
Class Method
@classmethod
cls
No
Yes
Modify class-level data
Static Method
@staticmethod
(none)
No
No
Utility methods (no access to instance/class)
5. Example Showing All Three
class Example:
count = 0
def __init__(self):
Example.count += 1
def instance_method(self):
return f"Instance method called. Instance count: {self.count}"
@classmethod
def class_method(cls):
return f"Class method called. Total instances: {cls.count}"
@staticmethod
def static_method():
return "Static method called. No instance or class data used."
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
1. Definition
A class method is defined using the decorator:
and it takes
clsas the first parameter (notself).2. Syntax
3. Usage Example
Explanation:
change_school()is called on the class, not on an instance.4. Difference Between Instance, Class, and Static Methods
self)cls)selfself.__class__@classmethodcls@staticmethod5. Example Showing All Three
Usage: