同一python版本的不同副本之间的行为不一致

2024-10-01 02:20:48 发布

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

我最近在玩下面的代码:

print(getattr(__builtins__, "__import__")("random"))

在我本地版本的Python上,它似乎如预期的那样工作:

<module 'random' from 'C:\\Users\\lkfjsa\\Programs\\Python3.6.1\\lib\\random.py'>

我的版本是:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32

然后我继续在repl.it上尝试同样的事情:Code Here

我能找到的关于该版本的最多信息是:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

然后给出以下输出:

Traceback (most recent call last):
  File "python", line 1, in <module>
AttributeError: 'dict' object has no attribute '__import__'

我真的很困惑。。。有人想解释一下吗


Tags: 代码frompyimport版本onlibrandom
2条回答

因为可能是由于repl.it的沙盒实现或者类似的东西,他们的__builtins__版本实际上是一个dict

   type(__builtins__)
=> <class 'dict'>
   __builtins__['__import__']
=> <built-in function __import__>
   __builtins__['__import__']('random')
=> <module 'random' from '/usr/local/lib/python3.6/random.py'>

名称__builtins__的值是一个实现细节:

As an implementation detail, most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module [the builtins module] or the value of this module’s __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.

https://docs.python.org/3/library/builtins.html

相关问题 更多 >