Inheritance and init method in Python

PythonInheritanceInit

Python Problem Overview


I'm begginer of python. I can't understand inheritance and __init__().

class Num:
    def __init__(self,num):
        self.n1 = num

class Num2(Num):
    def show(self):
        print self.n1

mynumber = Num2(8)
mynumber.show()

RESULT: 8

This is OK. But I replace Num2 with

class Num2(Num):
    def __init__(self,num):
        self.n2 = num*2
    def show(self):
        print self.n1,self.n2

RESULT: Error. Num2 has no attribute "n1".

In this case, how can Num2 access n1?

Python Solutions


Solution 1 - Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

> When a class defines an __init__() > method, class instantiation > automatically invokes __init__() for > the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

Solution 2 - Python

When you override the init you have also to call the init of the parent class

super(Num2, self).__init__(num)

https://stackoverflow.com/questions/576169/understanding-python-super

Solution 3 - Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Solution 4 - Python

Since you don't call Num.__init__ , the field "n1" never gets created. Call it and then it will be there.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYugo KamoView Question on Stackoverflow
Solution 1 - PythonMario DuarteView Answer on Stackoverflow
Solution 2 - PythonMauro RoccoView Answer on Stackoverflow
Solution 3 - PythonSacchit JaiswalView Answer on Stackoverflow
Solution 4 - PythonDanny MilosavljevicView Answer on Stackoverflow