correct way to use super (argument passing)

前端 未结 3 1626
迷失自我
迷失自我 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 16:52

    If you're going to have a lot of inheritence (that's the case here) I suggest you to pass all parameters using **kwargs, and then pop them right after you use them (unless you need them in upper classes).

    class First(object):
        def __init__(self, *args, **kwargs):
            self.first_arg = kwargs.pop('first_arg')
            super(First, self).__init__(*args, **kwargs)
    
    class Second(First):
        def __init__(self, *args, **kwargs):
            self.second_arg = kwargs.pop('second_arg')
            super(Second, self).__init__(*args, **kwargs)
    
    class Third(Second):
        def __init__(self, *args, **kwargs):
            self.third_arg = kwargs.pop('third_arg')
            super(Third, self).__init__(*args, **kwargs)
    

    This is the simplest way to solve those kind of problems.

    third = Third(first_arg=1, second_arg=2, third_arg=3)
    

提交回复
热议问题