Skip to main content
 首页 » 编程设计

python之重新定义在函数内不起作用的打印函数

2025年05月04日26kenshinobiy

我正在用 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 

有谁知道为什么这在函数中不起作用?
非常感谢任何有关如何修复它的建议。

请您参考如下方法:

所有你需要的是非本地并且忘记你创建的所有其他变量吧catstr:

def execute(lst): 
    def print(s): 
        nonlocal catstr 
        catstr += s 
    catstr = "" 
    for item in lst: 
        s = item 
        exec(s) 
    return catstr 

这给你:

In [1]: paste 
def execute(lst): 
    def print(s): 
        nonlocal catstr 
        catstr += s 
    catstr = "" 
    for item in lst: 
        s = item 
        exec(s) 
    return catstr 
 
## -- End pasted text -- 
 
In [2]: list = ["print('Wow!')\n", "print('Great!')\n", "print('Epic!')\n"] 
 
In [3]: execute(lst) 
Out[3]: 'Wow!Great!Epic!' 

函数中发生的任何事情都是函数的本地,因此您无需担心重置任何内容。如果您碰巧想要设置打印引用,您可以使用 old_print = __builtins__.print。

如果你想在不需要打印调用的情况下打印你的函数,请使用 __builtins__.print 进行打印:

def execute(lst): 
    catstr = "" 
    def print(s): 
        nonlocal catstr 
        catstr += s 
    for s in lst: 
        exec(s) 
    __builtins__.print(catstr)