为什么直接修改dict会返回未定义的结果?

2024-03-29 00:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在读《开始Python》这本书。其中提到:

In general, you should not modify the dictionary returned by vars because, according to the official Python documentation, the result is undefined. In other words, you might not get the result you’re after.

我很困惑。你知道吗

As vars()获取指定对象的__dict__。 该范围内的所有变量都基于__dict__。当修改它时,它怎么会被称为undefined?你知道吗

我这样做了:

>>> x = 0
>>> vars()['x'] += 2
>>> x
>>> 2

在有人改变x的值之前,这个x会保持2的值在那个范围内吗?你知道吗

那么,这里的result is undefined是什么意思?你知道吗


Tags: theinyoubydictionaryisnotresult
2条回答

也许documentation确实回答了你的问题:

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, classes use a dictproxy to prevent direct dictionary updates).

作为the documentation states

Without an argument, vars() acts like locals().

切换到locals,然后:

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

请注意,“may not”;undefined确切地说,对于应该发生的事情没有确切的定义。换言之,它不能保证,您不应该编写依赖它的代码(无论哪种方式)。你知道吗

相关问题 更多 >