【华为云技术分享】python教程:猴子补丁

猴子补丁指在运行时修改类或者模块,而不是改动定义类或者模块的源代码。

假设有预先定义的类A:

1 class Apple:
2     def __init__(self):
3         self._color = 'red'
4     def get_color(self):
5         return self._color

为类A打猴子补丁,即在运行时修改类A,例如:

1 def set_color(apple, color):
2     apple._color = color
3     
4 Apple.set_color = set_color

在运行时可以调用新设置的函数

image.png

作者:冰糖柠萌

posted @ 2020-03-19 17:55  华为云官方博客  阅读(219)  评论(0编辑  收藏  举报