+ 3

How to invoke all parents classes constructors in python ?

I am searching for better way to invoke all constructors of parents classes the below code works but I think there is better way to invoke all parents classes constructors. And please explain the super.init parts of the code. class A: def __init__(self, name): self.name = name class B: def __init__(self, city): self.city = city class C: def __init__(self, color): self.color = color class D(A, B, C): def __init__(self, name, city, color, age): super().__init__(name) super(A, self).__init__(city) super(B, self).__init__(color) self.age = age obj = D('samip', 'sam', 22, 'brown') print(obj.name) print(obj.city) print(obj.age) print(obj.color)

23rd Nov 2020, 3:46 PM
Samip Karki
Samip Karki - avatar
2 Réponses
+ 1
You can also call the init directly through the use of the class like; class D(A, B, C): def __init__(self, name, city, color, age): A.__init__(self, name) B.__init__(self, city) C.__init__(self, color) self.age = age This can, however, cause issues with further inheritance. Your use of super() is correct in this case, since super() will search the next object(s) in the mro (method resolution order). For more info: https://docs.python.org/3/library/functions.html#super
23rd Nov 2020, 9:50 PM
ChaoticDawg
ChaoticDawg - avatar
0
ChaoticDawg thank you very much for your answer I know the method you suggested. I am asking if there is another way of inheriting using super() in above code.
24th Nov 2020, 11:42 AM
Samip Karki
Samip Karki - avatar