您的位置:首页 > 其它

猴子补丁

2016-08-03 21:22 183 查看

A MonkeyPatch is a piece of Python code which extends or modifies other code at runtime (typically at startup).


A simple example looks like this:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
return "ook ook eee eee eee!"

SomeClass.speak = speak


For instance, consider a class that has a method
get_data
. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it.

However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the
get_data
method with a stub that returns some fixed data.

Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: