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

后端 未结 4 574
情话喂你
情话喂你 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:28

    The reason is all the arguments are already unpacked into kwargs and it is a dict now. and you are trying to pass it to a normal variables.

    def bun(args,kwargs):
    print 'i am here'
    print kwargs
    
    def fun(*args,**kwargs):
    print kwargs
    bun(*args,**kwargs)
    
     fun(hill=3,bi=9) # will fail.
    
    
    def bun(*args,**kwargs):
    print 'i am here'
    print kwargs
    
    def fun(*args,**kwargs):
    print kwargs
    bun(*args,**kwargs) # will work.
    
    
    
    fun(hill=3,bi=9)
    

    Try making the modification at

    class Foo(object):
        def __init__(self, *value1, **value2):
    # do something with the values
            print 'I think something is being called here'
            print value1, value2
    
    
    class MyFoo(Foo):
        def __init__(self, *args, **kwargs):
    # do something else, don't care about the args
            print args, kwargs
            super(MyFoo, self).__init__(*args, **kwargs)
    
    
    foo = MyFoo('Python', 2.7, stack='overflow'
    

    should work..!

提交回复
热议问题