有什么方法可以回到原来的功能吗?

cha*_*pkr 1 python function

假设我想通过应用某些公式来暂时替换某个类的某些动作something.action,

something.action = apply(something.action)
Run Code Online (Sandbox Code Playgroud)

稍后,我想something通过执行类似的操作将原始操作方法应用回实例

something.action = ...
Run Code Online (Sandbox Code Playgroud)

我该怎么做到这一点?

dam*_*ois 8

我想你可以简单地保存原始功能并写入

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)

  • @Chan不会只要"apply"做它应该做的事情 - 创建something.action的副本并返回它.如果它"就地"更改了操作,那么它被错误地用作函数而不是就地过程,然后整个信息丢失,因此您需要复制该函数:http://stackoverflow.com/questions/6527633/如何-可以-I-使-A-deepcopy的对的一函数式的Python (3认同)