Python Multilevel Inheritance

📔 : Python 🔗

Multilevel Inheritance में किसी class द्वारा किसी दूसरी class को ही Inherit किया जाता है then उस child class को किसी तीसरी class द्वारा inherit किया जाता है , इस तरह से एक tree structure बनकर तैयार होता है।


इस तरह के Inheritance में जो last child class होती है उसमे बाकी सभी parent class की सभी properties और methods होते हैं।


for example - A कोई class है जिसे B class inherit कर रही है, और C एक तीसरी class है जो B class को inherit कर रही है। इस तरह से C class में वो सभी properties और methods होंगे जो A , B class class में present हैं।


Multilevel inheritance को आप नीचे दिए गए graph की help से समझ सकते हैं।

Python Multilevel Inheritence


Python Multilevel Inheritance Example

Copy Fullscreen Close Fullscreen Run
# class A.
class A :
  def classa_fun(self) :
    print('Function in class A')

# class B that extends class A.
class B(A) :
  def classb_fun(self) :
    print('Function in class B')

# class C that extends class B.
class C(B) :
  def classc_fun(self) :
    print('Function in class C')

# now we can access all the functions using class C object that are in class A and B.
obj = C()
obj.classa_fun()
obj.classb_fun()
obj.classc_fun()
Output
C:\Users\Rahulkumar\Desktop\python>python multilevel_inhert.py
Function in class A
Function in class B
Function in class C

तो कुछ इस तरह से Python में multilevel inheritance work करती है।

Add __init__() Method

अगर आप सभी classes में __init__() method add करते हैं तो सभी child class में आपको super() या Parent class के name के साथ __init__() method को call करना पड़ेगा।
See Example -

Copy Fullscreen Close Fullscreen Run
# class A.
class A :
  def __init__(self) :
    print('Constructor in class A')

# class B that extends class A.
class B(A) :
  def __init__(self) :
    A.__init__(self)
    print('Constructor in class B')

# class C that extends class B.
class C(B) :
  def __init__(self) :
    super().__init__()
    print('Constructor in class C')

#just initialize the Object , so that all constructor could be run.
obj = C()
Output
C:\Users\Rahulkumar\Desktop\python>python multilevel_inhert.py
Constructor in class A
Constructor in class B
Constructor in class C

Note : जब parent class के __init__() method को Parent Class के name के साथ call करते हैं तो child class का object pass करना पड़ता है , और अगर super() method से call करते हैं तो child class का object नहीं pass करना पड़ता है।

I Hope, आप Python में Multilevel Inheritance के बारे में अच्छे से समझ गए होंगे।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers