OOP Python

OOP Python


2 min read

OOP stands for Object-Oriented Programming. It's a programming paradigm that revolves around the concept of "objects," which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).

1. Classes and Objects:

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

    def drive(self):
        print(f"Driving {self.make} {self.model}")

# Create instances of the Car class
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Accord")

# Call the drive method on the instances
car1.drive()  # Output: Driving Toyota Camry
car2.drive()  # Output: Driving Honda Accord

2. Inheritance:

Inheritance allows a class (subclass) to inherit attributes and methods from another class (superclass). It promotes code reusability and establishes an "is-a" relationship between classes.

class ElectricCar(Car):
    def __init__(self, make, model, battery_capacity):
        super().__init__(make, model)
        self.battery_capacity = battery_capacity

    def charge(self):
        print(f"Charging {self.make} {self.model} with {self.battery_capacity} kWh")

electric_car = ElectricCar("Tesla", "Model S", 100)
electric_car.drive()  # Inherited method from Car class
electric_car.charge()  # New method in ElectricCar class

3. Polymorphism:

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility and extensibility in code by allowing methods to behave differently based on the object they are called on.

class Shape:
    def area(self):

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

# Polymorphic function
def print_area(shape):
    print(f"Area: {shape.area()}")

# Usage
rectangle = Rectangle(5, 4)
circle = Circle(3)

print_area(rectangle)  # Output: Area: 20

Did you find this article valuable?

Support Deven by becoming a sponsor. Any amount is appreciated!