假设我想通过应用某些公式来暂时替换某个类的某些动作something.action,
something.action = apply(something.action)
Run Code Online (Sandbox Code Playgroud)
稍后,我想something通过执行类似的操作将原始操作方法应用回实例
something.action = ...
Run Code Online (Sandbox Code Playgroud)
我该怎么做到这一点?
我想你可以简单地保存原始功能并写入
tmp = something.action
something.action = apply(something.action)
Run Code Online (Sandbox Code Playgroud)
然后,以后
something.action = tmp
Run Code Online (Sandbox Code Playgroud)
例:
class mytest:
def action(self):
print 'Original'
a = mytest()
a.action()
tmp = a.action
def apply(f):
print 'Not the ',
return f
a.action = apply(a.action)
a.action()
a.action = tmp
a.action()
Run Code Online (Sandbox Code Playgroud)
这使
$ python test.py
Original
Not the Original
Original
Run Code Online (Sandbox Code Playgroud)