CONSTRUCTOR IN INHERITANCE IN PYTHON PROGRAMMING

5개월 전

The output when executed is as follows:

In python when sub class inherits the super class, it will access all the methods defined in the super class but it won't access the constructor in the parent class. When we create object of subclass, it will call its own default constructor not the parent class. So to access the init method of the parent class, we use a special function called super() that allows us to access the constructor of the super class. A simple program is shown here:

class Parent:
    
    def __init__(self):
        print("In Parent Class")
        
    def method1(self):
        print("Method1 1 is defined")
    def method2(self):
        print("Method 2 is defined")    
        
        
class Child(Parent):
    
    def __init__(self):
        super().__init__()
        print("In Child Class")
        
    def method3(self):
        print("Method 3 is defined")
    def method4(self):
        print("Method 4 is defined")   
        
C1=Child()



Screenshot_3.png

You can copy/paste the above code and execute it to see the output yourself in this web page.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
STEEMKR.COM IS SPONSORED BY
ADVERTISEMENT