亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更改內置函數 - 打印

更改內置函數 - 打印

回首憶惘然 2023-09-26 16:41:19
我正在嘗試更改 python 的 print 內置函數。我試圖實現此目的的原因是因為我的應用程序有一個詳細的 sys.argv,并且我想使用 print 來控制臺輸出消息,無論詳細信息是 True 還是 False。我嘗試使用創建新函數,但出現遞歸錯誤:>>> import builtins>>> def new_print(*args, **kwargs):...     print('print:', *args, **kwargs)... >>> old_print = builtins.print>>> old_print(1)1>>> builtins.print = new_print>>> print(1)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 2, in new_print  File "<stdin>", line 2, in new_print  File "<stdin>", line 2, in new_print  [Previous line repeated 996 more times]RecursionError: maximum recursion depth exceeded我嘗試過使用 sys.stdout():>>> import builtins>>> import sys>>> def new_print(*args, **kwargs):...     sys.stdout(*args, **kwargs)... >>> old_print = builtins.print>>> old_print(1)1>>> builtins.print = new_print>>> print(1... )Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 2, in new_printTypeError: '_io.TextIOWrapper' object is not callable盡管使用了這些選項,但似乎沒有一個能正常工作。我需要所有模塊文件都可以訪問新的打印功能,而無需每次都導入它。這就是為什么我嘗試更改內置函數,但我不確定在init .py 文件中更改此函數是否會對我的其他文件產生影響。拜托,如果您有任何可以幫助我的想法,請留在下面。
查看完整描述

1 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

你幾乎已經擁有了。調用old_print你的新函數:


def new_print(*args, **kwargs):

    old_print('print:', *args, **kwargs)


old_print = print

print = new_print


查看完整回答
反對 回復 2023-09-26
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號