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
?
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
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)
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í.
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