Types of Methods in Python Classes


Types of Methods in Python Classes

  1. Instance Method
  2. Class Method
  3. Static Method

1. Instance Method

  • Definition:
    Instance methods use the self keyword and work with instance variables.
  • Purpose:
    To modify or access the object’s attributes.

Program:
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 the cls keyword.
  • Purpose:
    To access or modify the class variables.

Program:
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 use self or cls.
  • 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
    

Post a Comment

0 Comments