Herencia y método init en Python


Soy principiante de Python. No puedo entender la herencia y __init__().

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

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

mynumber = Num2(8)
mynumber.show()

RESULTADO: 8

Esto está bien. Pero sustituyo Num2 por

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

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

En este caso, ¿cómo puede Num2 acceder a n1?

Author: Richard Hansen, 2011-03-02

3 answers

En la primera situación, Num2 está extendiendo la clase Num y como no está redefiniendo el método especial llamado __init__() en Num2, se hereda de Num.

Cuando una clase define un __init__() método, instanciación de clase invoca automáticamente __init__() para la instancia de clase recién creada.

En la segunda situación, ya que está redefiniendo __init__() en Num2 necesita llamar explícitamente al de la super clase (Num) si desea extender su comportamiento.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2
 91
Author: Mario Duarte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-02 11:12:42

Cuando anula el init también tiene que llamar al init de la clase padre

super(Num2, self).__init__(num)

Entendiendo Python super () con los métodos__ init _ _ ()

 23
Author: Mauro Rocco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

Como no llamas a Num.__init__, el campo "n1" nunca se crea. Llámalo y entonces estará allí.

 3
Author: Danny Milosavljevic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-27 17:50:49