在以下定义的函数中,
def a_function(x, dictionary = dict()):
if not dictionary:
print('Empty Dictionary')
dictionary['A'] = 1
dictionary['B'] = 2
return dictionary.get(x)
它接受'A'
or'B'
并返回1
or 2
。字典参数应该每次都初始化,但是当我运行它时,它是不可变的,因为一旦创建,它就不会再次启动。'Empty Dictionary'
只运行一次。为什么?
>> a_function('A')
Empty Dictionary
1
>> a_function('B')
2
Python文档指出:
执行功能定义时,默认参数值从左到右评估。
这意味着在定义函数时,表达式将被计算一次,并且每个调用都使用相同的“预先计算”值。
例如:
>>> import datetime
>>> def f(foo=datetime.datetime.now()):
... print(foo)
>>> f()
2020-01-21 05:21:35.084471
>>> f()
2020-01-21 05:21:35.084471
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句