Skip to main content
 首页 » 编程设计

python之用它的神奇行为掩盖内置变量

2025年05月04日33落叶无声

我无法关注这个statement in python tutorials :

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

请您参考如下方法:

在交互式提示中,_ 具有“神奇”的行为——它被设置为最后计算的任何表达式的值:

>>> 3 + 3 
6 
>>> _ 
6 

但是,如果您自己将某些内容分配给名为 _ 的变量,那么您只会“看到”该变量,而魔术变量将被隐藏(“屏蔽”):

>>> _ = 3 
>>> 3 + 3 
6 
>>> _ 
3 

发生这种情况是因为您的局部变量 _ 与具有魔术行为的变量无关,它恰好具有相同的名称。

所以不要那样做,无论如何不要在交互式提示中这样做。