Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Inheritance in Python

Inheritance in Python

Inheritance in Python is an object-oriented programming (OOP) concept where a child class (subclass) inherits properties and behaviors (methods) from a parent class (superclass).

  • This promotes code reuse, improves organization, and helps in creating hierarchical relationships between classes.

Syntax:

class Parent:
    # parent class members

class Child(Parent):
    # child class members

Benefits of Inheritance:

  • Code Reusability – Avoids rewriting code by reusing existing functionality.
  • Modularity – Promotes clean and maintainable code.
  • Extensibility – Easily extend base class behavior.
  • Overriding – Allows modifying or extending parent class behavior.
image 29

Single Inheritance is a type of inheritance in which a subclass (child class) inherits from only one superclass (parent class). This allows the child class to reuse the attributes and methods of a single parent class.

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Dog barks")

d = Dog()
d.speak()  # inherited
d.bark()   # own method

Multiple Inheritance is a type of inheritance in which a subclass inherits from more than one superclass. This allows the child class to access attributes and methods from all parent classes.

class Father:
    def skill(self):
        print("Gardening")

class Mother:
    def talent(self):
        print("Painting")

class Child(Father, Mother):
    pass

c = Child()
c.skill()
c.talent()

Multilevel Inheritance is a type of inheritance where a class is derived from another derived class. That is, a subclass inherits from a class which is already a subclass of another class, forming a chain of inheritance.

class Grandparent:
    def legacy(self):
        print("Land and House")

class Parent(Grandparent):
    def guidance(self):
        print("Life Advice")

class Child(Parent):
    def play(self):
        print("Playing video games")

c = Child()
c.legacy()
c.guidance()
c.play()
class A:
    def showA(self):
        print("A")

class B(A):
    def showB(self):
        print("B")

class C:
    def showC(self):
        print("C")

class D(B, C):  # D has multiple and multilevel inheritance
    def showD(self):
        print("D")

d = D()
d.showA()
d.showB()
d.showC()
d.showD()

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *