【问题标题】:Python3.4 multi inheritance call specific constructorsPython3.4多继承调用特定构造函数
【发布时间】:2016-06-19 08:03:42
【问题描述】:

这是我的情况,我应该写什么来代替评论?

提前谢谢你,如果我问了一些已经回答的问题,很抱歉。

我已经在寻找答案但没有成功。

#!/usr/bin/python3.4
class A(object):
    def __init__(self):
        print("A constructor")

class B(A):
    def __init__(self):
        super(B, self).__init__()
        print("B constructor")

class C(A):
    def __init__(self):
        super(C, self).__init__()
        print("C constructor")

class D(B,C):
    def __init__(self):
        """ what to put here in order to get printed:
            B constructor
            C constructor
            A constructor
            D constructor
                  or                
            C constructor
            B constructor
            A constructor
            D constructor
                   ?
            (notice I would like to print once 'A constructor')
        """
        print("D constructor")

if __name__ == "__main__":
    d = D()

【问题讨论】:

    标签: constructor python-3.4 multiple-inheritance


    【解决方案1】:

    我发现稍微改变类构造函数代码就可以满足我的需要:

    #!/usr/bin/python3.4
    class A(object):
        def __init__(self):
            print("A constructor")
    
    class B(A):
        def __init__(self):
            if self.__class__ == B:
                A.__init__(self)
            print("B constructor")
    
    class C(A):
        def __init__(self):
            if self.__class__ == C:
                A.__init__(self)
            print("C constructor")
    
    class D(B,C):
        def __init__(self):
            B.__init__(self)        #
            C.__init__(self)        # if B constructor should be
            A.__init__(self)        # called before of C constructor
            print("D constructor")  #
    
    #        C.__init__(self)       #
    #        B.__init__(self)       # if C constructor should be
    #        A.__init__(self)       # called before of B constructor
    #        print("D constructor") #
    
    if __name__ == "__main__":
        d = D()
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 2011-11-16
      • 2013-06-01
      相关资源
      最近更新 更多