Method Resolution Order in case of Base Classes Having different init params

前端 未结 5 1210
刺人心
刺人心 2021-01-20 05:52

I am trying to understand MRO in Python. Although there are various posts here, I am not particularly getting what I want. Consider two classes A and B

5条回答
  •  春和景丽
    2021-01-20 06:13

    To understand this, try without any arguments:

    class BaseClass(object):
        def __init__(self):
            print("BaseClass.__init__")
    
    class A(BaseClass):
        def __init__(self):
            print("A.__init__")
            super(A, self).__init__()
    
    class B(BaseClass):
        def __init__(self):
            print("B.__init__")
            super(B, self).__init__()
    
    class C(A, B):
        def __init__(self):
            print("C.__init__")
            super(C, self).__init__()
    

    When we run this:

    >>> c = C()
    C.__init__
    A.__init__
    B.__init__
    BaseClass.__init__
    

    This is what super does: it makes sure everything gets called, in the right order, without duplication. C inherits from A and B, so both of their __init__ methods should get called, and they both inherit from BaseClass, so that __init__ should also be called, but only once.

    If the __init__ methods being called take different arguments, and can't deal with extra arguments (e.g. *args, **kwargs), you get the TypeErrors you refer to. To fix this, you need to make sure that all the methods can handle the appropriate arguments.

提交回复
热议问题