简体   繁体   English

为什么 Python 3 中函数中的初始化字典参数是不可变的?

[英]Why is an initialized dictionary argument in a function in Python 3 immutable?

In the following defined function,在下面定义的函数中,

def a_function(x, dictionary = dict()):
    if not dictionary:
        print('Empty Dictionary')
        dictionary['A'] = 1
        dictionary['B'] = 2
    return dictionary.get(x)

it takes in 'A' or 'B' and returns 1 or 2 .它接受'A''B'并返回12 The dictionary argument is supposed to be initialized each time, but when I run it, it is immutable, in that once created, it doesn't start again.字典参数应该每次都初始化,但是当我运行它时,它是不可变的,因为一旦创建,它就不会再次启动。 'Empty Dictionary' is run only once. 'Empty Dictionary'只运行一次。 Why?为什么?

>> a_function('A')
Empty Dictionary
1
>> a_function('B')
2

Python docs states that: Python 文档指出:

Default parameter values are evaluated from left to right when the function definition is executed.执行函数定义时从左到右计算默认参数值。

This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call .这意味着在定义函数时,表达式被计算一次,并且每次调用都使用相同的“预计算”值

For example:例如:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM