🔧 Method in OOPs
Last Updated: 05 Sept 2025
Methods = functions inside a class.
They define behavior of the object.
- Functions → Global, can be used anywhere.
- Methods → Belong to a class, always connected to an object.
Hinglish Tip 🗣: Agar class ek "Car" hai → attributes = color, speed; methods = start(), stop().
✏ Types of Methods in Python
- Instance Methods (most common)
- Class Methods
- Static Methods
💡 1. Instance Method
- Works on object (instance)
- Always takes
selfas first parameter
class Student:
def __init__(self, name):
self.name = name
def greet(self): # Instance Method
print(f"Hello, my name is {self.name}")
s1 = Student("Amit")
s1.greet() # Hello, my name is Amit
💡 2. Class Method
- Works on class instead of object.
- Define using
@classmethoddecorator. - Always takes
clsas first parameter.
Example 1.
class Student:
school_name = "DPS" ## Class Variable
@classmethod
def info(cls):
print("School Name:", cls.school_name)
Student.info() # School Name: DPS
Example 2. Class Method as a Constructor
class Student:
def __init__(self, name):
self.name = name
@classmethod
def create(cls, name):
return cls(name)
s1 = Student.create("Amit") # s1 = Student("Amit")
print(s1.name) # Amit
💡 3. Static Method
- Does not depend on object or class.
- Define using
@staticmethoddecorator. - No self, no cls.
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(5, 7)) # 12
Example
Let, Make a Car class with:
- Instance method: details() (prints brand and model)
- Class method: show_type(), total_cars()
- Static method: mileage(km, fuel) (returns km/ltr)
class Car:
type = "Car"
total = 0
def __init__(self, brand, model):
self.brand = brand
self.model = model
Car.total += 1 # Class Variable
def details(self): # Instance Method
print(f"{self.brand} {self.model}")
@classmethod
def show_type(cls): # Class Method
print("This is a", cls.type)
@classmethod
def total_cars(cls):
return cls.total
@staticmethod
def mileage(km, fuel): # Static Method
return km / fuel
c1 = Car("Tesla", "Model 3")
c1.details() # Tesla Model 3
Car.show_type() # This is a Car
print(Car.mileage(500, 25)) # 20.0
print(c1.mileage(500, 25)) # 20.0
print(Car.total_cars()) # 1
Note: You Can check method and class variables using
__dict__
print(c1.__dict__) # {'brand': 'Tesla', 'model': 'Model 3'}
print(Car.__dict__) # {'type': 'Car', 'total': 1}