Mixins, multi-inheritance, constructors and data

I have a class:

class A(object): def __init__(self, *args): # impl 

Also "mixin", basically a different class with some data and methods:

 class Mixin(object): def __init__(self): self.data = [] def a_method(self): # do something 

Now I create a subclass of A with mixin:

 class AWithMixin(A, Mixin): pass 

My problem is that I want the A and Mixin constructors to be called. I believed that giving AWithMixin its own constructor in which super was called, but superclass constructors have different argument lists. What is the best resolution?

+6
source share
2 answers
 class A_1(object): def __init__(self, *args, **kwargs): print 'A_1 constructor' super(A_1, self).__init__(*args, **kwargs) class A_2(object): def __init__(self, *args, **kwargs): print 'A_2 constructor' super(A_2, self).__init__(*args, **kwargs) class B(A_1, A_2): def __init__(self, *args, **kwargs): super(B, self).__init__(*args, **kwargs) print 'B constructor' def main(): b = B() return 0 if __name__ == '__main__': main() 
  • Constructor A_1
  • Constructor A_2
  • B constructor
+10
source

I am also pretty new to OOP, but what is the problem with this code:

 class AWithMixin(A, Mixin): def __init__(self, *args): A.__init__(self, *args) Mixin.__init__(self) 
+8
source

Source: https://habr.com/ru/post/890153/


All Articles