解释Python中的monkey patching是什么意思?

PHPz
发布: 2023-08-19 11:53:16
转载
1222人浏览过

解释python中的monkey patching是什么意思?

Monkey patching is the technique of dynamic modification of a piece of code at the run time. Actually by doing monkey patch we change the behavior of code but without affecting the original source code.

历史

Monkey patch(猴子补丁)一词源自游击补丁(guerrilla patch),guerrilla几乎意味着大猩猩,可以定义猴子物种。游击补丁指的是秘密地进行变更。但是猴子补丁听起来更容易发音,所以现在被称为“Monkey patch”。在“Monkey-patch”一词中,monkey定义了dynamic(动态)这个词。

Monkey patching in python

Monkey patching in python refers to modifying or updating a piece of code or class or any module at the runtime. In simple words, we can change the behavior or working of a class/ module at the runtime without changing the whole python code. But sometimes monkey patching is considered bad practice because the definition of object does not accurately describe how the object is behaving in the code.

Example

class first:
   def print(self)
      print(“hello world”)
登录后复制

输出

If we run the above code it will generate the following output −

阿里妈妈·创意中心
阿里妈妈·创意中心

阿里妈妈营销创意中心

阿里妈妈·创意中心 0
查看详情 阿里妈妈·创意中心

立即学习Python免费学习笔记(深入)”;

Hello world
登录后复制

代码猴子补丁后

Example

Import monkey
def monkey_function(self):
   print(“Hello world”)
# updating the print() with monkey_function()
monkey.A.print = monkey_function

# revoking method print() as method monkey_function()
obj = monkey.A()
obj print()
登录后复制

输出

If we run the above code it will generate the following output −

立即学习Python免费学习笔记(深入)”;

Hello world
登录后复制

以上就是解释Python中的monkey patching是什么意思?的详细内容,更多请关注php中文网其它相关文章!

相关标签:
python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号