Where is the default parameter in Python function

后端 未结 5 1576
情深已故
情深已故 2021-01-05 08:52

I think many people have seen the python\'s function which receives default parameters. For example:

def foo(a=[]):
    a.append(3)
    return a
5条回答
  •  滥情空心
    2021-01-05 09:19

    It's attached to the function object, see foo.func_defaults:

    >>> foo()
    >>> foo.func_defaults
    ([3],)
    >>> foo()
    >>> foo.func_defaults
    ([3, 3],)
    

    In case if you want to get the mapping of a onto [], you can access foo.func_code:

    defaults = foo.func_defaults
    # the args are locals in the beginning:
    args = foo.func_code.co_varnames[:foo.func_code.co_argcount] 
    def_args = args[-len(defaults):]  # the args with defaults are in the end
    print dict(zip(def_args, defaults)) # {'a': []}
    

    (But, apparently, the yak's version is better.)

提交回复
热议问题