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 |
但是假设我只想替换
1 2 3 | >>> def times_eight(self, arg): ... return arg * 8 >>> s.make = ??? |
你可以创建新的实例
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 |
方法
1 | s.make = lambda arg: times_eight(s, arg) |
(你可以简化