代码之家  ›  专栏  ›  技术社区  ›  user6022430

Python3.4多重继承调用特定构造函数

  •  0
  • user6022430  · 技术社区  · 10 年前

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

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

    我一直在寻找答案,但没有成功。

    #!/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()
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   user6022430 user6022430    10 年前

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

    #!/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()