monkey-patching python一个实例方法

monkey-patching python an instance method

本问题已经有最佳答案,请猛点这里访问。

我正在尝试修补一个类实例,但不太明白如何修补一个类方法没问题。

1
2
3
4
5
6
7
8
9
10
11
>>> class Simple(object):
...     def make(self, arg):
...         return arg * 2
...
>>> s = Simple()
>>> def times_four(self, arg):
...   return arg * 4
...
>>> Simple.make = times_four
>>> s.make(10)
40

但是假设我只想替换make,那么最简单的方法是什么?

1
2
3
>>> def times_eight(self, arg):
...   return arg * 8
>>> s.make = ???


你可以创建新的实例times_eightby using its method"__get__特殊法:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> class Simple(object):
...     def make(self, arg):
...         return arg * 2
...
>>> s = Simple()
>>> def times_eight(self, arg):
...     return arg * 8
...
>>> s.make = times_eight.__get__(s, Simple)
>>> s.make(10)
80
>>> type(s.make)
<type 'instancemethod'>
>>>


哦!P></

1
2
3
4
>>> import types
>>> s.make = types.MethodType(times_eight, s, Simple)
>>> s.make(10)
80


方法selfonly get the automatically when passed Arg(not received from the class from the实例dict),我知道你need to通安1 -精氨酸功能有:P></

1
s.make = lambda arg: times_eight(s, arg)

(你可以简化functools.partialthat with)。P></