假设我想通过将一些公式应用于something.action
来暂时替换某个类的某些动作,
something.action = apply(something.action)
稍后,我想通过执行类似的操作将原始操作方法应用回实例something
something.action = ...
我该如何做到这一点?
答案 0 :(得分:8)
我认为您可以直接保存原始函数并编写
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
答案 1 :(得分:0)
最好的方法是将操作存储在同一个对象中,但名称不同:
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中所拥有的)
答案 2 :(得分:0)
这样的事情怎么样而不是弄乱你的对象?
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