python猴子补丁,在程序运行时修改类或模块,而不改动源码
1 import re 2 3 class Monkey(object): 4 def __init__(self, myStr): 5 self.myStr = myStr 6 7 def search(self): 8 myRe = "Hello" 9 return re.search(myRe, self.myStr, re.I).span() 10 11 if __name__ == "__main__": 12 m1 = Monkey("Hello World") 13 print(m1.search()) 14 def MonkeySearch(self): 15 myRe = "World" 16 return re.search(myRe, self.myStr, re.I|re.M).span() 17 Monkey.search = MonkeySearch 18 m2 = Monkey("Hello World") 19 print(m2.search())
输出结果:
(0, 5)
(6, 11)