合作多重继承问题

End*_*age 6 python inheritance multiple-inheritance

这是对该问题的扩展,并提出了一个问题,您,我的StackOverflowers同学,希望能够为我提供帮助。从所引用的问题中,考虑最终的代码示例:

class A(object):
    def __init__(self):
        print "entering A"
        print "leaving A"

class B(object):
    def __init__(self):
        print "entering B"
        super(B, self).__init__()
        print "leaving B"

class C(A,B):
    def __init__(self):
        print "entering c"
        super(C, self).__init__()
        print "leaving c"
Run Code Online (Sandbox Code Playgroud)

如发布者所述,在初始化C时,__init__永远不会调用B 的for。考虑到Raymond Hettinger的帖子,的代码class A应修改为也可以调用super().__init__()

class A(object):
    def __init__(self):
        print "entering A"
        super(A, self).__init__()
        print "leaving A"
Run Code Online (Sandbox Code Playgroud)

到目前为止我们都很好。但是,如果我们的类的__init__函数接受参数怎么办?假设所有__init__函数都接受一个参数,为了保持一致性,我们将其简称为foo,代码现在为:

class A(object):
    def __init__(self, foo):
        print "entering A"
        super(A, self).__init__(foo)
        print "leaving A"

class B(object):
    def __init__(self, foo):
        print "entering B"
        super(B, self).__init__(foo)
        print "leaving B"

class C(A,B):
    def __init__(self, foo):
        print "entering c"
        super(C, self).__init__(foo)
        print "leaving c"
Run Code Online (Sandbox Code Playgroud)

在这里,我们遇到了障碍。初始化任何A,B或C类时,我们最终都object.__init__使用单个参数调用,该参数foo会出错TypeError: object.__init__() takes no parameters。但是,删除其中一个super().__init__功能将意味着在多重继承的情况下,这些类不再协作。

毕竟,我的问题是如何解决这个问题?似乎在没有将任何参数传递给__init__函数的情况下,多重继承都被破坏了。

更新:

Rob在评论中建议删除关键字参数(在Raymond H的帖子中引用)。在多重继承的情况下,直到更改代码为止,这实际上非常有效。如果您的函数之一不再使用关键字参数之一,并且在不修改调用函数的情况下停止剥离它,则您仍然会收到上述TypeError。因此,对于大型项目而言,这似乎是一个脆弱的解决方案。

小智 2

__init__诚然,这个解决方案可能不是最Pythonic或最理想的,但是为对象创建一个包装类,像这样允许您在继承中传递参数:

class Object(object):
    def __init__(self,*args,**kwargs):
        super(Object,self).__init__()

class A(Object):
    def __init__(self,*args,**kwargs):
        super(A,self).__init__(*args,**kwargs)

class B(Object):
    def __init__(self,*args,**kwargs):
        super(B,self).__init__(*args,**kwargs)

class C(A,B):
    def __init__(self,*args,**kwargs):
        super(C,self).__init__(*args,**kwargs)
Run Code Online (Sandbox Code Playgroud)