Inheritance in Python

    python-logo

    Inheritance is a powerful feature in object-oriented programming that allows you to create new classes that are modified versions of existing classes. Inheritance makes it easier to reuse code and make your programs more efficient and organized.

    Creating a Subclass

    In Python, you can create a subclass by defining a new class and specifying the existing class as its parent:

    class ParentClass:
        def my_method(self):
            print("This is a method in the parent class")
    class ChildClass(ParentClass):
    pass
    

    In this example, ParentClass is the parent class, and ChildClass is the subclass. The pass keyword is used to indicate that the subclass has no additional methods or attributes.

    Overriding Methods

    You can modify the behavior of a method in the subclass by defining a method with the same name:

    class ParentClass:
    def my_method(self):
    print("This is a method in the parent class")
    
    class ChildClass(ParentClass):
    def my_method(self):
    print("This is a method in the child class")
    

    In this example, the my_method() method in the subclass ChildClass overrides the method of the same name in the parent class ParentClass.

    Calling the Parent Method

    You can call the method of the parent class from the subclass using the super() function:

    class ParentClass:
    def my_method(self):
    print("This is a method in the parent class")
    
    class ChildClass(ParentClass):
    def my_method(self):
    super().my_method()
    print("This is a method in the child class")
    

    In this example, the super().my_method() line calls the my_method() method of the parent class ParentClass.

    Conclusion

    Inheritance in Python allows you to create new classes that are modified versions of existing classes. By using inheritance, you can make your code more efficient and organized by reusing code and modifying existing functionality.