Header Ads Widget

Ticker

6/random

Python Inheritance

Python inheritance


In Python, inheritance is a mechanism that allows a new class to inherit attributes and methods from an existing class. This promotes code reuse and supports the concept of a hierarchy of classes. Here's an explanation with examples:


1. Simple Inheritance:


```python

class Animal:

    def __init__(self, name):

        self.name = name

    def speak(self):

        print("Generic animal sound")

 

# Dog class inherits from Animal

class Dog(Animal):

    def speak(self):

        print("Woof!")

 

# Creating objects of the base and derived classes

generic_animal = Animal(name="Generic Animal")

my_dog = Dog(name="Buddy")

 

# Calling methods from both classes

generic_animal.speak()

my_dog.speak()

```


In this example, the `Dog` class inherits from the `Animal` class. The `speak` method is overridden in the `Dog` class.


2. Accessing Base Class Methods:


```python

class Rectangle:

    def __init__(self, length, width):

        self.length = length

        self.width = width

    def area(self):

        return self.length * self.width

 

# Square class inherits from Rectangle

class Square(Rectangle):

    def __init__(self, side_length):

        super().__init__(length=side_length, width=side_length)

 

# Creating objects of both classes

rectangle = Rectangle(length=5, width=3)

square = Square(side_length=4)

 

# Accessing methods from both classes

print(f"Rectangle Area: {rectangle.area()}")

print(f"Square Area: {square.area()}")

```


Inheritance allows the `Square` class to reuse the `area` method from the base class `Rectangle`.


3. Overriding and Super():


```python

class Vehicle:

    def start_engine(self):

        print("Engine started")

 

# Car class inherits from Vehicle

class Car(Vehicle):

    def start_engine(self):

        super().start_engine()

        print("Car engine started")

 

# Creating objects of both classes

generic_vehicle = Vehicle()

my_car = Car()

 

# Calling overridden method and using super()

generic_vehicle.start_engine()

my_car.start_engine()

```


Here, the `Car` class overrides the `start_engine` method of the base class `Vehicle`. `super()` is used to call the overridden method from the base class.


Inheritance is a powerful concept in object-oriented programming, allowing for the creation of hierarchies of classes and promoting code reuse. It enhances the structure and organization of code in a more modular way.

Post a Comment

0 Comments