Why can't pass *args and **kwargs in __init__ of a child class

后端 未结 4 607
情话喂你
情话喂你 2020-12-09 09:56

To understand *args and **kwargs I made some searchs about, when I fell on this question *args and **kwargs?

The answer below the chosen answer caught my attention,

4条回答
  •  醉话见心
    2020-12-09 10:24

    I think it is worth adding that this can be used to simplify the __init__ signatures in the child classes. The positional arguments are pealed off from left to right so if you add them to the front and pass the rest to args and kwargs you can avoid mistakes from forgetting to add them explicitly to each of the children. There is some discussion about if that is an acceptable exception "explicit is better than implicit" here. For long lists of args in deep hierarchy this may be clearer and easier to maintain.

    To modify this example, I add not_for_Foo to the front of MyFoo and pass the rest through super.

    class Foo(object):
        def __init__(self, a_value1, a_value2, a_stack=None, *args, **kwargs):
            """do something with the values"""
            super(Foo, self).__init__(*args, **kwargs) # to objects constructor fwiw, but object.__init__() takes no args
            self.value1 = a_value1
            self.value2 = a_value2
            self.stack = a_stack
            return
    
        def __str__(self):
            return ', '.join(['%s: %s' % (k, v) for k, v in self.__dict__.items()])
    
    
    class MyFoo(Foo):
        def __init__(self, not_for_Foo, *args, **kwargs):
            # do something else, don't care about the args
            super(MyFoo, self).__init__(*args, **kwargs)
            self.not_for_Foo = not_for_Foo # peals off
            self.myvalue1 = 'my_' + self.value1 # already set by super
    
    
    if __name__ == '__main__':
    
        print 'Foo with args'
        foo = Foo('Python', 2.7, 'my stack')
        print foo
    
        print '\nMyFoo with kwargs'
        myfoo = MyFoo('my not for foo', value2=2.7, value1='Python', stack='my other stack')
        print myfoo
    
    
    $ python argsNkwargs.py 
    Foo with args
    value2: 2.7, value1: Python, stack: my stack
    
    MyFoo with kwargs
    myvalue1: my_Python, not_for_Foo: my not for foo, value2: 2.7, value1: 
    Python, stack: my other stack
    

    -lrm

提交回复
热议问题