作者:892974506_bdb55d_896 | 来源:互联网 | 2023-05-19 14:29
Ithinkmanypeoplehaveseenthepythonsfunctionwhichreceivesdefaultparameters.Forexample:
I think many people have seen the python's function which receives default parameters. For example:
我想很多人都看过python的函数接收默认参数。例如:
def foo(a=[]):
a.append(3)
return a
If we call this function using foo(), the output will append integer '3' each time after the call.
如果我们使用foo()调用此函数,则每次调用后输出都会附加整数“3”。
When this function is defined, a function object named 'foo' is defined in the current environment, and also the default parameter values are evaluated at this time. Every time when the function is called without a parameter, the evaluated parameter value will be changed according to the code.
定义此函数时,在当前环境中定义名为“foo”的函数对象,此时还会计算默认参数值。每次在没有参数的情况下调用函数时,将根据代码更改评估的参数值。
My question is, where is this evaluated parameter exist? Is it in the function object or it is in the method object when calling the function? Since everything in python is a object, there must be some place to hold the name->value binding of 'a'-->evaluated parameter. Am I over-thinking this problem?
我的问题是,这个评估参数在哪里存在?它是在函数对象中还是在调用函数时在方法对象中?因为python中的所有东西都是一个对象,所以必须有一些地方来保存'a' - > evaluate参数的name-> value绑定。我是否过度思考这个问题?
5 个解决方案
10
As others already said, the default values are stored in the function object.
正如其他人已经说过的那样,默认值存储在函数对象中。
For example, in CPython you can do this:
例如,在CPython中,您可以这样做:
>>> def f(a=[]):
... pass
...
>>> f.func_defaults
([],)
>>> f.func_code.co_varnames
('a',)
>>>
However, co_varnames
may contain more than names of args so it needs further processing and these attributes might not even be there in other Python implementations. Therefore you should use the inspect
module instead which takes care of all implementation details for you:
但是,co_varnames可能包含多个args名称,因此需要进一步处理,这些属性可能甚至不存在于其他Python实现中。因此,您应该使用inspect模块,它会为您处理所有实现细节:
>>> import inspect
>>> spec = inspect.getargspec(f)
>>> spec
ArgSpec(args=['a'], varargs=None, keywords=None, defaults=([],))
>>>
The ArgSpec
is a named tuple so you can access all values as attributes:
ArgSpec是一个命名元组,因此您可以将所有值作为属性访问:
>>> spec.args
['a']
>>> spec.defaults
([],)
>>>
As the documentation says, the defaults
tuple always corresponds to the n last arguments from args
. This gives you your mapping.
正如文档所说,默认元组总是对应于args中的n个最后一个参数。这为您提供了映射。
To create a dict you could do this:
要创建一个dict,你可以这样做:
>>> dict(zip(spec.args[-len(spec.defaults):], spec.defaults))
{'a': []}
>>>