我需要在运行时更改另一个函数内的调用函数。
考虑以下代码:
一个用户编写了代码
如何解决这个问题?
一个可能的解决方案是像这里所做的那样编辑字节码:http://web.archive.org/web/20140306210310/http://www.jonathon-vogel.com/posts/patching_function_bytecode_with_python,但我想知道是否有更简单的方法。
考虑以下代码:
def now():
print "Hello World!"
class Sim:
def __init__(self, arg, msg):
self.msg = msg
self.func = arg
self.patch(self.func)
def now(self):
print self.msg
def run(self):
self.func()
def patch(self, func):
# Any references to the global now() in func
# are replaced with the self.now() method.
def myfunc():
now()
Then ...
>>> a = Sim(myfunc, "Hello Locals #1")
>>> b = Sim(myfunc, "Hello Locals #2")
>>> b.run()
Hello Locals #2
>>> a.run()
Hello Locals #1
一个用户编写了代码
myfunc()
,它调用了全局定义的函数 now()
,我不能编辑它。但是我想让它调用 Sim
实例的方法。因此,我需要在运行时“修补” myfunc()
函数。如何解决这个问题?
一个可能的解决方案是像这里所做的那样编辑字节码:http://web.archive.org/web/20140306210310/http://www.jonathon-vogel.com/posts/patching_function_bytecode_with_python,但我想知道是否有更简单的方法。
now
和myfunc
是否在同一个模块中定义?您是否关心其他对now
的使用会受到影响?如果它们在不同的模块中,myfunc
如何访问now
函数?如果它执行的是from somemodule import now ... now()
,与import somemodule ... somemodule.now()
,所需的方法可能会有所不同。 - Weeble