开发者

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_meth开发者_高级运维od(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?


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜