muckabout
muckabout

Reputation: 1941

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?

Upvotes: 6

Views: 5177

Answers (2)

kecske
kecske

Reputation: 649

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

Upvotes: 10

utdemir
utdemir

Reputation: 27226

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)

Upvotes: 9

Related Questions