Hi Pythonistas!
When working with classes in Python, you might have come across instance methods, class methods, and static methods. These three types of methods have different behaviors and use cases. Let’s break them down in the simplest way possible!
1. Instance Methods (Normal Methods)
These are the most common methods in Python classes. They:
✅ Operate on an instance of the class
✅ Can access and modify instance attributes
✅ Receive self as the first argument
code
class Car:
def __init__(self, brand):
self.brand = brand # Instance attribute
def show_brand(self): # Instance method
return f"This car is a {self.brand}"
my_car = Car("Tesla")
print(my_car.show_brand())
Output
This car is a Tesla
Here, show_brand() is an instance method because it uses self to access the instance attribute brand.
2. Class Methods (@classmethod)
✅ Work on the class itself, not on an instance
✅ Can modify class-level attributes
✅ Receive cls (class) as the first argument instead of self
class Car:
manufacturer = "Unknown" # Class attribute
@classmethod
def set_manufacturer(cls, name):
cls.manufacturer = name # Modifies class-level attribute
Car.set_manufacturer("Toyota")
print(Car.manufacturer) # Output: Toyota
Output
Toyota
Here, set_manufacturer() is a class method that changes the manufacturer for all instances of Car.
✅ Best Use Case: When you need to modify or access class-level attributes instead of instance attributes.
3. Static Methods (@staticmethod)
✅ Behave like regular functions, but live inside a class
✅ Don’t need access to self (instance) or cls (class)
✅ Can be used when the method does not modify instance or class data
code
class Car:
@staticmethod
def general_info():
return "Cars have wheels and an engine."
print(Car.general_info()) # Output: Cars have wheels and an engine.
Output
Cars have wheels and an engine.
Here, general_info() doesn’t need access to instance or class attributes, making it a static method.
✅ Best Use Case: When a function logically belongs to a class but doesn’t depend on instance or class attributes.
Comparison Table
Feature | Instance Method | Class Method | Static Method |
---|---|---|---|
Access self ? |
✅ Yes (Instance attributes) | ❌ No | ❌ No |
Access cls ? |
❌ No | ✅ Yes (Class attributes) | ❌ No |
Modifies instance attributes? | ✅ Yes | ❌ No | ❌ No |
Modifies class attributes? | ❌ No | ✅ Yes | ❌ No |
Works without instance? | ❌ No | ✅ Yes | ✅ Yes |
When to Use What?
Use an instance method when you need to work with an object’s attributes.
Use a class method when you need to modify class attributes.
Use a static method when you need a helper function inside a class, but it doesn’t depend on any class or instance attributes.
Hope this makes it easy to understand!, Please share your suggestions at afsal@parseltongue.co.in