gpt4 book ai didi

python - 为什么导入模块与覆盖打印冲突?

转载 作者:太空宇宙 更新时间:2023-11-04 09:01:25 25 4
gpt4 key购买 nike

我想自动向我的 print 语句添加时间戳(在 Python 2.x 中)by overriding it .它有效,除非我导入一个也包含覆盖的模块。

我的主文件testa.py:

from __future__ import print_function
import datetime
import testb

def print(*args, **kwargs):
__builtins__.print(datetime.datetime.now(), ' ', end='')
return __builtins__.print(*args, **kwargs)

print("from main file")
testb.MyClass()

辅助文件testb.py

from __future__ import print_function
import datetime

def print(*args, **kwargs):
__builtins__.print(datetime.datetime.now(), ' ', end='')
return __builtins__.print(*args, **kwargs)

class MyClass():
def __init__(self):
print("from helper file")

运行测试时:

2014-07-29 09:43:54.375000  from main file
Traceback (most recent call last):
File "C:/testa.py", line 10, in <module>
testb.MyClass()
File "C:\testb.py", line 15, in __init__
print("from helper file")
File "C:\testb.py", line 10, in print
__builtins__.print(datetime.datetime.now(), ' ', end='')
AttributeError: 'dict' object has no attribute 'print'

我认为在导入 testb 时,它的 print 定义与 testa 中的定义有些冲突,但这是我的想法达到了极限.

最佳答案

不要依赖于 __builtins__。相反,import __builtin__ 并使用 __builtin__.print。看这里:https://docs.python.org/2/reference/executionmodel.html

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.

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.

关于python - 为什么导入模块与覆盖打印冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25010541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com