猴子补丁
主要用于修改第三方代码,适用于采用继承的方式不合适的情况。
动态修改一个类中的方法,除了采用类的继承,重写方法外;
最简单的方式就是给类打个补丁。这对于在运行中替换或者添加方法是非常有用的。
▶给类打补丁
影响范围:此类的所有实例。
class Test:
def HW(self):
print('Hello!')
def HW_N(self):
print('world!')
def other(self):
print('Andy!')
# 取代现存方法
Test.HW = HW_N
# 新加方法
Test.howl = howl
test=Test()
print(test.other())
▶给实例打补丁
动态修改类的某个实例中的方法,仅当前实例可用。
import types
class Test:
def HW(self):
print('Hello!')
def Other(self, kkk):
self.HW()
print(kkk)
inst_test = Test()
inst_test.Other= types.MethodType(Other, inst_test )
print(inst_test.Other("kkk_kkk"))
------山的那一边

浙公网安备 33010602011771号