correct way to use super (argument passing)

前端 未结 3 1633
迷失自我
迷失自我 2020-11-29 16:29

So I was following Python\'s Super Considered Harmful, and went to test out his examples.

However, Example 1-3, which is supposed to show the correct way of calling

3条回答
  •  长情又很酷
    2020-11-29 17:09

    As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

    class A(object):
        def __init__(self, *args, **kwargs):
            print "A"
            super(A, self).__init__(*args, **kwargs)
    
    class B(object):
        def __init__(self, *args, **kwargs):
            print "B"
            super(B, self).__init__(*args, **kwargs)
    
    class C(A):
        def __init__(self, arg, *args, **kwargs):
            print "C","arg=",arg
            super(C, self).__init__(*args, **kwargs)
    
    class D(B):
        def __init__(self, arg, *args, **kwargs):
            print "D", "arg=",arg
            super(D, self).__init__(*args, **kwargs)
    
    class E(C,D):
        def __init__(self, arg, *args, **kwargs):
            print "E", "arg=",arg
            super(E, self).__init__(*args, **kwargs)
    
    print "MRO:", [x.__name__ for x in E.__mro__]
    E(10, 20, 30)
    

提交回复
热议问题