Python:重新定义函数,使其引用自己的自身 [英] Python: Redefine function so that it references its own self
问题描述
说我有一些功能 fun
,其实际代码主体不在我的控制范围内.我可以创建一个新函数,该函数在调用 fun
(即
Say I have got some function fun
, the actual code body of which is out of my control. I can create a new function which does some preprocessing before calling fun
, i.e.
def process(x):
x += 1
return fun(x)
如果我现在希望 process
代替 fun
,以便以后对 fun
的所有调用,我都需要做类似的事情>
If I now want process
to take the place of fun
for all future calls to fun
, I need to do something like
# Does not work
fun = process
但是,这不起作用,因为这会产生一个循环引用问题,因为现在从 fun
的正文中调用了 fun
.我发现的一种解决方案是在 process
内引用 fun
的副本,如下所示:
This does not work however, as this creates a cyclic reference problem as now fun
is called from within the body of fun
. One solution I have found is to reference a copy of fun
inside of process
, like so:
# Works
import copy
fun_cp = copy.copy(fun)
def process(x):
x += 1
return fun_cp(x)
fun = process
但是这个解决方案使我感到困扰,因为我真的不知道Python如何构造函数的副本.我猜我的问题与使用继承和 super
函数扩展类方法的问题相同,但是在这里我没有类.
but this solution bothers me as I don't really know how Python constructs a copy of a function. I guess my problem is identical to that of extending a class method using inheritance and the super
function, but here I have no class.
如何正确执行此操作?我认为这是一项足够常见的任务,应该或多或少有一些惯用的解决方案,但是我没有运气找到它.
How can I do this properly? I would think that this is a common enough task that some more or less idiomatic solution should exist, but I have had no luck finding it.
推荐答案
Python不是 构造函数的副本. copy.copy(fun)
仅返回 fun
;区别在于,您将其保存到 fun_cp
变量中,该变量与您将 process
保存到的变量不同,因此当它保存在 fun_cp
中时,进程
尝试寻找它.
Python is not constructing a copy of your function. copy.copy(fun)
just returns fun
; the difference is that you saved that to the fun_cp
variable, a different variable from the one you saved process
to, so it's still in fun_cp
when process
tries to look for it.
我将执行与您所做的类似的操作,将原始函数保存到其他变量中,而无需使用复制":
I'd do something similar to what you did, saving the original function to a different variable, just without the "copy":
original_fun = fun
def fun(x):
x += 1
return original_fun(x)
如果要将相同的包装应用于多个函数,则定义装饰器并执行 fun = decorate(fun)
更具可重用性,但一次性而言,它比必要的工作多,并且额外的缩进级别.
If you want to apply the same wrapping to multiple functions, defining a decorator and doing fun = decorate(fun)
is more reusable, but for a one-off, it's more work than necessary and an extra level of indentation.
这篇关于Python:重新定义函数,使其引用自己的自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!