Skip to main content
 首页 » 编程设计

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

2025年05月04日22xxx_UU

我最近在研究以下代码:

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

我真的很困惑……有人愿意解释一下吗?

请您参考如下方法:

因为可能由于 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'>