Inheritance: Understanding Inheritance in Python Programming Language, How to Create Subclasses, and Use Superclass Members

python-logo

Inheritance is a powerful feature in object-oriented programming that allows a class to inherit properties and methods from another class. In Python, inheritance is implemented using the syntax:

class Subclass(Superclass):
    # subclass definition

Here, Subclass is the class that inherits from Superclass. The subclass can access all the attributes and methods of the superclass. This feature makes it easier to create new classes that are similar to existing ones, without having to duplicate code.

To create a subclass, define a new class with the same name as the superclass, and specify the superclass in parentheses after the class name. The subclass can then override or add to the methods and attributes inherited from the superclass.

class Animal:
    def __init__(self):
        self.name = "Animal"
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        self.name = "Dog"
    def speak(self):
        print("Dog barks")

d = Dog()
print(d.name)
d.speak()

In this example, Animal is the superclass and Dog is the subclass. The Dog class overrides the speak method of the Animal class. When d.speak() is called, the output is “Dog barks”.

To use the superclass members in the subclass, you can call the superclass method using the super() function. This is particularly useful when you want to add functionality to the superclass method, instead of replacing it entirely.

class Animal:
    def __init__(self):
        self.name = "Animal"
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def __init__(self):
        super().__init__()
        self.name = "Dog"
    def speak(self):
        super().speak()
        print("Dog barks")

d = Dog()
d.speak()

In this example, the Dog class uses the super() function to call the speak method of the Animal class before printing “Dog barks”. This means that the Dog class can use the speak method of the Animal class and add new functionality to it.

In conclusion, inheritance is a powerful feature in Python that allows you to create subclasses that inherit properties and methods from a superclass. You can then use the superclass members in the subclass and override or add to them as needed. This feature makes it easier to create new classes that are similar to existing ones, without having to duplicate code.

Total
0
Shares
Previous Post
python-logo

Classes and Objects

Next Post
python-logo

Explanation of Modules in Python Programming Language

Related Posts