我正在python 3.x中寫一個python腳本,我需要重新定義print
函數。當我在我的口譯員那裏工作時,它工作正常。但是當我使用相同的代碼創建一個函數時,它會發出錯誤。重定義打印功能不能在一個函數內工作
這裏是我的代碼:
list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
old_print = print
def print(s):
global catstr
catstr += s
catstr = ""
for item in list:
s = item
exec(s)
print = old_print
catstr
>> 'Wow!Great!Epic!'
正如你可以看到我已經得到了我想要的結果:'Wow!Great!Epic!'
現在我讓使用相同的代碼的函數:
def execute(list):
old_print = print
def print(s):
global catstr
catstr += s
catstr = ""
for item in list:
s = item
exec(s)
print = old_print
return catstr
現在當我使用以下代碼運行此功能:
list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"]
execute(list)
我得到以下錯誤:
old_print = print
UnboundLocalError: local variable 'print' referenced before assignment
有誰知道爲什麼這是不是一個函數內的工作?
任何建議如何解決它將不勝感激。
這是第一行,你定義打印在函數中,作爲一個函數,你在使用old_print等什麼? –
你的問題的目的是什麼?或者這只是出於好奇? – BPL
@BPL這是直接相關的作爲他們昨天問的後續問題[這裏](http://stackoverflow.com/questions/39460882/how-to-get-execution-of-python-print-statements-as-a -string) – idjaw