简体   繁体   English

删除后我从哪里访问__name__?

[英]From where am I accessing __name__ after deleting it?

In my Python Shell, deleting __name__ makes it become 'builtins' . 在我的Python Shell中,删除__name__使其成为'builtins' __name__ 'builtins' Although, checking with globals confirms that I am not refering to __name__ from some global variable. 虽然,用globals检查确认我没有从某个全局变量__name__

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> __name__
'__main__'
>>> del __name__
>>> __name__
'builtins'
>>> globals()[__name__]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'builtins'

My guess is that we are using it from some closure. 我的猜测是我们从一些关闭中使用它。 How is this behaviour taking place? 这种行为是如何发生的?

All names are looked up first from local variables, then global variables, then __builtins__ , which is available everywhere. 首先从局部变量查找所有名称,然后是全局变量,然后是__builtins__ ,它随处可见。 It's where all the built in functions are. 这是所有内置功能的所在。

In[6]: __builtins__
Out[6]: <module 'builtins' (built-in)>
In[7]: __builtins__.__name__
Out[7]: 'builtins'
In[8]: __builtins__.len
Out[8]: <function len>

As you can probably guess from the __name__ , you're accessing the name of the builtins module . 您可以从__name__ ,您正在访问builtins模块的名称。

Whenever you access a variable and that variable isn't found in any closure, the local scope or the global scope, the lookup falls back to the builtins. 无论何时访问变量并且在任何闭包,本地范围或全局范围中都找不到该变量,查找都会回退到内置函数。 This is why you can access things like min or max or type even though they're not global variables: 这就是为什么你可以访问像minmax这样的东西或者type它们,即使它们不是全局变量:

>>> 'min' in globals()                                                                   
False
>>> min
<built-in function min>      
>>> __builtins__.min
<built-in function min>                                                    

The same thing happens with __name__ . __name__发生同样的事情。 Initially, there's a __name__ variable defined in the global scope: 最初,在全局范围内定义了一个__name__变量:

>>> globals()['__name__']
'__main__'

But once that name is deleted with del __name__ , the lookup in the globals fails and falls back to the builtins - so you end up with the name of the builtins module. 但是一旦使用del __name__删除了该名称,全局变量中的查找将失败并返回到内置函数 - 因此您最终会得到builtins模块的名称。

>>> del __name__
>>> __name__
'builtins'
>>> __builtins__.__name__
'builtins'

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

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