Skip to main content
 首页 » 编程设计

python之为什么 Python 在调用导入函数时找不到内置打印函数

2024年10月17日7jyk

拿这个ma​​in.py:

from __future__ import print_function 
 
from sub import print 
 
print("hello, world") 

和这个sub.py:

from __future__ import print_function 
 
def print(*args, **kwargs): 
    return __builtins__.print(*args, **kwargs) 

使用 Python 2.7.9,运行 main.py 并得到:

Traceback (most recent call last): 
File "main.py", line 5, in <module> 
    print("hello, world") 
File "/Users/ien/Studio/songifier/sub.py", line 4, in print 
    return __builtins__.print(*args, **kwargs) 
AttributeError: 'dict' object has no attribute 'print' 

为什么以及如何进行这项工作?

注意:这是一个用于隔离问题的人工示例,它出现在日志记录上下文中,其中 print 函数有时会执行一些花哨的日志记录,而其他时候只想调用内置的 -在打印功能中。

请您参考如下方法:

试试这个:

import __builtin__ 
from __future__ import print_function 
 
def print(*args, **kwargs): 
    return __builtin__.print(*args, **kwargs) 

>>> print 
<function print at 0x7f80cd622668> 
>>> print("Hello", "world", sep="\n") 
Hello 
world 

python docs 中的这段摘录可以更好地解释您所看到的错误的原因。 :

By default, when in the __main__ module, __builtins__ is the built-in module __builtin__ (note: no 's'); when in any other module, __builtins__ is an alias for the dictionary of the __builtin__ module itself.

__builtins__ can be set to a user-created dictionary to create a weak form of restricted execution.

CPython implementation detail: Users should not touch __builtins__; it is strictly an implementation detail. Users wanting to override values in the builtins namespace should import the __builtin__ (no 's') module and modify its attributes appropriately. The namespace for a module is automatically created the first time a module is imported.