Types of Methods in Python Classes
- Instance Method
- Class Method
- Static Method
1. Instance Method
- Definition:
Instance methods use theself
keyword and work with instance variables. - Purpose:
To modify or access the object’s attributes.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
# Instance method to display car details
def display(self):
print("Car Brand:", self.brand)
print("Car Model:", self.model)
# Creating an object of Car
car1 = Car("Toyota", "Corolla")
car1.display()
Output:
Car Brand: Toyota
Car Model: Corolla
2. Class Method
- Definition:
Class methods use the@classmethod
decorator and thecls
keyword. - Purpose:
To access or modify the class variables.
class Car:
total_cars = 0 # Class variable
def __init__(self, brand, model):
self.brand = brand
self.model = model
Car.total_cars += 1
@classmethod
def update_total_cars(cls, new_count):
cls.total_cars = new_count
print("Total cars updated to:", cls.total_cars)
# Accessing the class method
Car.update_total_cars(5)
Output:
Total cars updated to: 5
3. Static Method
- Definition:
Static methods use the@staticmethod
decorator. They do not useself
orcls
. - Purpose:
To perform utility tasks that do not access instance or class variables.
Program:
class Calculator:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
# Using static methods without creating an object
print("Addition:", Calculator.add(5, 3))
print("Multiplication:", Calculator.multiply(4, 2))
Output:
Addition: 8
Multiplication: 8
0 Comments