
正文
python中的monkey-patching
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
这个技巧我很少用过。
但知道无防。
在运行时改变函数或类的行为,
一般用猴子补丁,原类,装饰器都可以实现。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import types
class Class(object):
def add(self, x, y):
return x + y
inst = Class()
def not_exactly_add(self, x, y):
return x * y
print inst.add(3, 4)
Class.add = not_exactly_add
print inst.add(3, 4)
class TClass(object):
def add(self, x, y):
return x + y
def become_more_powerful(self):
old_add = self.add
def more_powerful_add(self, x, y):
return old_add(x, y) + 1
self.add = types.MethodType(more_powerful_add, self)
inst = TClass()
inst.old_add = inst.add
print inst.add(3, 4)
inst.become_more_powerful()
print inst.add(3, 4)
inst.become_more_powerful()
inst.become_more_powerful()
inst.become_more_powerful()
print inst.add(3, 4)
print inst.old_add(3, 4)






