Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixins, multi-inheritance, constructors, and data

I have a class:

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

Also a "mixin", basically another 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 the mixin:

class AWithMixin(A, Mixin):
    pass

My problem is that I want the constructors of A and Mixin both called. I considered giving AWithMixin a constructor of its own, in which the super was called, but the constructors of the super classes have different argument lists. What is the best resolution?

like image 225
muckabout Avatar asked Jun 09 '11 14:06

muckabout


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()
  1. A_1 constructor
  2. A_2 constructor
  3. B constructor
like image 107
kecske Avatar answered Oct 13 '22 03:10

kecske


I'm fairly new to OOP too, but what is the problem on this code:

class AWithMixin(A, Mixin):
    def __init__(self, *args):
        A.__init__(self, *args)
        Mixin.__init__(self)
like image 42
utdemir Avatar answered Oct 13 '22 03:10

utdemir