↓ Skip to main content
Python

Python: Inheritance

·2 mins

Inheritance is a mechanism in object-oriented programming (OOP) that allows you to create new classes that are derived from existing classes. The derived class inherits attributes and behaviors from the base class, and can also have additional attributes and behaviors of its own.

Here’s an example of inheritance in Python:

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

    def make_sound(self):
        print("Some sound")

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

    def make_sound(self):
        print("Woof!")

In this example, the Animal class is the base class and the Dog class is the derived class. The Dog class inherits the name attribute from the Animal class, and also has its own breed attribute.

The make_sound method in the Dog class overrides the make_sound method in the Animal class. This is known as method overriding.

The super() function is used to call the __init__ method of the base class, allowing the derived class to inherit the attributes and behaviors of the base class.

You can create instances of the Dog class just like any other class:

dog = Dog("Mydo", "Belgian")
dog.make_sound()
# Output: Woof!

This creates a new instance of the Dog class, with the name attribute set to “Mydo” and the breed attribute set to “Belgian”. The make_sound method is then called on the dog instance to produce the output “Woof!”.

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Python: Class

·1 min
Learning to write Python code? A Python class is a blueprint for creating objects. It defines a set of attributes and methods that can be used to manipulate those attributes. Here’s an example of a simple Python class:

Python: Decorators

·1 min
Let’s learn about decorators @iamdecorator Decorators are used to modify or extend the behavior of functions and classes. They are useful for wrapping a function or class with additional functionality, such as logging, access control, performance measurement, or adding attributes. This can reduce code duplication, increase readability and maintainability.

Python: Interface

·1 min
n Python, unlike some other programming languages, there is no explicit syntax for defining interfaces. However, you can create a similar concept by defining an abstract base class (ABC) that contains abstract methods. An abstract method is a method that is declared in a base class, but has no implementation. Subclasses of the abstract base class must implement these abstract methods.