1

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

something.action = apply(something.action)

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

something.action = ...

我应该如何做到这一点?

4

3 回答 3

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
于 2013-10-19T19:33:07.227 回答
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 中所拥有的全部)

于 2013-10-19T19:48:10.960 回答
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
于 2013-10-19T20:13:33.590 回答