Can I in OOP in Python implement method __init__ in inherited class? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

Can I in OOP in Python implement method __init__ in inherited class?

20th Feb 2019, 3:53 PM
Elvis Isaev
3 Respuestas
+ 4
Yes, you can, but if you do it like this, it's completely overwritten, so you can only pass the one legs argument. Solution: def __init__(self, name, color, legs): super().__init__(name, color) self.legs = legs First you let Dog's init take all three args. Then super() invokes the class from which Dog inherited from. So you're calling Wolf's init with all the args it can handle, and the rest you deal with by hand.
20th Feb 2019, 4:14 PM
HonFu
HonFu - avatar
+ 5
Dog.__init__ takes 2 args but you give 4 args You should add 2 more parameters and add "super().__init__(name, color)" to call Wolf.__init__
20th Feb 2019, 4:33 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 2
Yes, magic methods work similar to regular methods, if magic isn't defined in a class it is searched from it's super class.
20th Feb 2019, 5:58 PM
Seb TheS
Seb TheS - avatar