Python之猴子补丁

1.在运行时,对属性,方法,函数等进行动态替换
2.其目的往往是为了通过替换,修改来增强,扩展原有代码的能力
#test2.py
class Person:
    def get_score(self):
        ret = {'english':80,'history':100,'chinese':150}
        return  ret
#test3.py
def get_score(self):
    return dict(name=self.__class__.__name__,english=100,chinese=40,history=120)
from test1 import Person
from test2 import get_score
def momkeypatch4Person():
    Person.get_score = get_score

momkeypatch4Person()

if __name__ == "__main__":
    print(Person().get_score())
上例中,假设Person类get_score方法是从数据库拿数据,但是测试的时候不方便,使用猴子补丁,替换了get_socre方法,返回模拟数据

  

猜你喜欢

转载自www.cnblogs.com/harden13/p/9061264.html
今日推荐