什么是猴子补丁? [英] What is monkey patching?

查看:54
本文介绍了什么是猴子补丁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解,什么是猴子补丁或猴子补丁?

I am trying to understand, what is monkey patching or a monkey patch?

这是否类似于方法/运算符的重载或委托?

Is that something like methods/operators overloading or delegating?

这些东西有什么共同点吗?

Does it have anything common with these things?

推荐答案

不,它不像任何这些东西.它只是在运行时动态替换属性.

No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.

例如,考虑一个具有方法 get_data 的类.此方法执行外部查找(例如,在数据库或 Web API 上),类中的各种其他方法调用它.但是,在单元测试中,您不想依赖外部数据源 - 因此您将 get_data 方法动态替换为返回一些固定数据的存根.

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.

因为 Python 类是可变的,而方法只是类的属性,您可以随心所欲地执行此操作 - 事实上,您甚至可以以完全相同的方式替换模块中的类和函数.

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.

但是,正如一位评论者所指出的,在使用monkeypatching时要小心:

But, as a commenter pointed out, use caution when monkeypatching:

  1. 如果除了您的测试逻辑之外还有其他任何东西调用 get_data,它也会调用您的猴子补丁替换而不是原始版本——这可能是好的也可能是坏的.小心点.

  1. If anything else besides your test logic calls get_data as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware.

如果某些变量或属性在您替换它时也指向 get_data 函数,则该别名不会改变其含义并继续指向原始 get_data.(为什么?Python 只是将类中的名称 get_data 重新绑定到某个其他函数对象;其他名称绑定根本不受影响.)

If some variable or attribute exists that also points to the get_data function by the time you replace it, this alias will not change its meaning and will continue to point to the original get_data. (Why? Python just rebinds the name get_data in your class to some other function object; other name bindings are not impacted at all.)

这篇关于什么是猴子补丁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆