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

假设有预先定义的类A:

class Apple:
    def __init__(self):
        self._color = 'red'
    def get_color(self):
        return self._color

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

def set_color(apple, color):
    apple._color = color
    
Apple.set_color = set_color

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

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