Sep-06-2017, 08:56 AM
Hi All,
I was trying to understand Inheritance concept in Python.
When I wrote the code without using super(), I was getting desired results. You can see that below
I am getting following error:
I was trying to understand Inheritance concept in Python.
When I wrote the code without using super(), I was getting desired results. You can see that below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Base1( object ): def __init__( self ): self .name1 = "Peter" def showName1( self ): print ( self .name1) class Base2( object ): def __init__( self ): self .name2 = "John" def showName2( self ): print ( self .name2) class Child(Base2, Base1): def __init__( self ): self .name3 = "Sagar" Base1.__init__( self ) Base2.__init__( self ) def showName3( self ): print ( self .name3) obj = Child() obj.showName1() obj.showName2() obj.showName3() |
Output:Peter
John
Sagar
But when I wrote super() in place of writing class name in Child class's __init__() function,1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Base1( object ): def __init__( self ): self .name1 = "Peter" def showName1( self ): print ( self .name1) class Base2( object ): def __init__( self ): self .name2 = "John" def showName2( self ): print ( self .name2) class Child(Base2, Base1): def __init__( self ): self .name3 = "Sagar" super (Child, self ).__init__() def showName3( self ): print ( self .name3) obj = Child() obj.showName1() obj.showName2() obj.showName3() |
I am getting following error:
Error:Traceback (most recent call last):
File "D:\Sagar\Python Related\Scripts\MultipleInheritance.py", line 25, in <module>
obj.showName1()
File "D:\Sagar\Python Related\Scripts\MultipleInheritance.py", line 6, in showName1
print(self.name1)
AttributeError: 'Child' object has no attribute 'name1'
Is super() not used in case of Multiple Inheritance ?