比方说,我想暂时通过应用一些公式something.action
这样更换一类的一些行动,有什么办法可以回到原来的功能?
something.action = apply(something.action)
后来,我想通过做这样的事情到原来的操作方法适用回到实例something
something.action = ...
我该如何做到这一点?
比方说,我想暂时通过应用一些公式something.action
这样更换一类的一些行动,有什么办法可以回到原来的功能?
something.action = apply(something.action)
后来,我想通过做这样的事情到原来的操作方法适用回到实例something
something.action = ...
我该如何做到这一点?
我想你可以简单地保存原有的功能和写入
tmp = something.action
something.action = apply(something.action)
然后,后来
something.action = tmp
例子:
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()
这给
$ python test.py
Original
Not the Original
Original
要做到这一点
我尝试过,但我认为通过做'something.action = apply(something.action)',因为tmp被绑定到something.action,tmp也会改变为新的应用操作。 – chanpkr
@Chan不会,只要“应用”做它应该做的事情 - 创建something.action的副本并返回它。如果它将“就地”动作更改,而不是将其错误地用作函数而不是就地过程,那么整个信息都会丢失,因此您需要复制函数:http://stackoverflow.com/questions/6527633/我怎么能做一个在python中的函数的深层拷贝 – lejlot
@lejlot哦..那么你如何复制一个函数呢? – chanpkr
最好的办法是存储在同一个对象的动作,但有不同的名称:
something._old_action = something.action
something.action = apply(something._old_action) # this way you can still use it
something.action = lambda x: print(x) # or you can ignore it completely
do_some_stuff()
something.action = something._old_action
请注意,我们存储在该对象的旧动作,我们可以使用它。通过使用_开始名称,我们通知该属性是私有的(纯粹是一种惯例,但它是我们在Python中所有的)
这样的事情怎么样,而不是搞乱你的对象?
class Original(object):
def __init__(self):
self.x = 42
def hello(self):
print self.x
class OriginalWrapper(Original):
def __init__(self, original):
self.__class__ = type(original.__class__.__name__,
(self.__class__, original.__class__), {})
self.__dict__ = original.__dict__
def hello(self):
print self.x + 10
original = Original()
original.hello() #42
wrapped = OriginalWrapper(original)
wrapped.hello() #52
您是否确定手头的问题无法使用继承/包装而不是修补(混淆)对象来解决? –