In Python, instance methods and class methods are two types of methods used inside classes, and they differ in what they operate on and how they are called. Here’s a clear, interview-ready explanation:
1. Instance Method #
- Definition: A method that operates on a specific instance (object) of a class.
- First Parameter: Always
self, which refers to the instance. - Access: Can access instance attributes and class attributes.
Example:
filename.python
class Employee:
raise_amount = 1.1 # class attribute
def __init__(self, name, salary):
self.name = name
self.salary = salary
def apply_raise(self): # instance method
self.salary = int(self.salary * self.raise_amount)
return self.salary
emp = Employee("Aswini", 5000)
print(emp.apply_raise()) # 5500
Here, apply_raise() uses self.salary → operates on that particular object.
2. Class Method #
- Definition: A method that operates on the class itself, not on a specific object.
- First Parameter: Always
cls, which refers to the class. - Decorator:
@classmethod - Access: Can access class attributes, but not instance attributes unless passed explicitly.
Example:
filename.python
class Employee:
raise_amount = 1.1
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
Employee.set_raise_amount(1.2) # modifies class attribute for all instances
emp1 = Employee("Aswini", 5000)
emp2 = Employee("Kumar", 6000)
print(emp1.salary * emp1.raise_amount) # 6000
print(emp2.salary * emp2.raise_amount) # 7200
Here, set_raise_amount() changes the class-level attribute, affecting all instances.
Key Differences #
| Feature | Instance Method | Class Method |
|---|---|---|
| Access | Instance attributes | Class attributes |
| First parameter | self | cls |
| Decorator | None | @classmethod |
| Called on | Object instance | Class (or instance) |
| Use case | Behavior specific to object | Behavior affecting class as a whole |
Practical Use Case #
In a project I worked on:
- Instance methods handled individual user operations like
login()orupdate_profile(). - Class methods handled operations affecting the class, like creating users from a CSV file or changing system-wide settings (class attributes).
This separation of responsibilities keeps the code organized and modular.
