Python Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows you to create a new class (child class) that inherits attributes and methods from an existing class (parent class). This promotes code reuse and establishes a relationship between classes.


Creating a Parent Class

You define a parent class by creating a regular class. This class will serve as the base class for other classes.

Explanation of Code:

In this example, the Animal class has an initializer (__init__), a method speak which must be implemented by subclasses, and an info method that returns information about the animal. A parent class is defined just like any other class in Python. It contains methods and attributes that can be inherited by child classes.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclasses must implement this method")

    def info(self):
        return f"I am an animal named {self.name}"




Creating a Child Class

You define a child class by specifying the parent class in parentheses after the class name.

Explanation: A child class inherits attributes and methods from the parent class and can override or extend them. The Dog and Cat classes inherit from the Animal class and provide their own implementation of the speak method.

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"




Using the Child Classes

You can create instances of the child classes and use their inherited and overridden methods.

Explanation of Code:

Instances of child classes can access methods and attributes defined in the parent class as well as their own methods.

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.info())   # Output: I am an animal named Buddy
print(dog.speak())  # Output: Woof!
print(cat.info())   # Output: I am an animal named Whiskers
print(cat.speak())  # Output: Meow!




Extending the Child Class

You can add new methods or attributes to a child class that are not present in the parent class.

Explanation of Code:

Child classes can have additional functionality not defined in the parent class. The Bird class has an additional attribute can_fly and a new method fly, along with overriding the speak method.

class Bird(Animal):
    def __init__(self, name, can_fly=True):
        super().__init__(name)
        self.can_fly = can_fly

    def speak(self):
        return "Chirp!"

    def fly(self):
        return "I can fly!" if self.can_fly else "I cannot fly."

bird = Bird("Tweety")
print(bird.info())  # Output: I am an animal named Tweety
print(bird.speak()) # Output: Chirp!
print(bird.fly())   # Output: I can fly!




Python Inheritance Example Code

Explanation of Code:

This program creates an Animal class and its child classes Dog, Cat, and Bird. It demonstrates the inheritance of methods, overriding methods, and extending classes with new functionality.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclasses must implement this method")

    def info(self):
        return f"I am an animal named {self.name}"

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Bird(Animal):
    def __init__(self, name, can_fly=True):
        super().__init__(name)
        self.can_fly = can_fly

    def speak(self):
        return "Chirp!"

    def fly(self):
        return "I can fly!" if self.can_fly else "I cannot fly."

# Using the classes
dog = Dog("Mochi")
cat = Cat("Whiskers")
bird = Bird("Tweety")

print(dog.info())   # Output: I am an animal named Buddy
print(dog.speak())  # Output: Woof!
print(cat.info())   # Output: I am an animal named Whiskers
print(cat.speak())  # Output: Meow!
print(bird.info())  # Output: I am an animal named Tweety
print(bird.speak()) # Output: Chirp!
print(bird.fly())   # Output: I can fly!




Python Labs

Scroll to Top