p

python tutorial - Multilevel Inheritance | Multilevel Inheritance in Python - learn python - python programming



  • Multilevel inheritance is also possible in Python unlike other programming languages.
  • You can inherit a derived class from another derived class.
  • This is known as multilevel inheritance. In Python, multilevel inheritance can be done at any depth.
  • An example with corresponding visualization is given below.
class Base:
    pass

class Derived1(Base):
    pass

class Derived2(Derived1):
    pass

Image representation:

python multilevel inheritance

Example:1 Python Multilevel Inheritance:

#!/usr/bin/evn python

# Define a class as 'student'
class student:
    # Method
    def getStudent(self):
        self.name = input("Name: ")
        self.age = input("Age: ")
        self.gender = input("Gender: ")

# Define a class as 'test' and inherit base class 'student'
class test(student):
    # Method
    def getMarks(self):
        self.stuClass = input("Class: ")
        print("Enter the marks of the respective subjects")
        self.literature = int(input("Literature: "))
        self.math = int(input("Math: "))
        self.biology = int(input("Biology: "))
        self.physics = int(input("Physics: "))

# Define a class as 'marks' and inherit derived class 'test'
class marks(test):
    # Method
    def display(self):
        print("\n\nName: ",self.name)
        print("Age: ",self.age)
        print("Gender: ",self.gender)
        print("Study in: ",self.stuClass)
        print("Total Marks: ", self.literature + self.math + self.biology + self.physics)


m1 = marks()
# Call base class method 'getStudent()'
m1.getStudent()
# Call first derived class method 'getMarks()'
m1.getMarks()
# Call second derived class method 'display()'
m1.display()

Output:

Name: James
Age: 16
Gender: Male
Class: 10th
Enter the marks of the respective subjects
Literature: 50
Math: 60
Biology: 55
Physics: 46


Name:  James
Age:  16
Gender:  Male
Study in:  10th
Total Marks:  211

Example2: Python Multilevel Inheritance

class Animal:
def eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self):
print 'Barking...'
class BabyDog(Dog):
def weep(self):
print 'Weeping...'
d=BabyDog()
d.eat()
d.bark()
d.weep()

Output:

Eating...
Barking...
Weeping

Related Searches to Multilevel Inheritance in Python