问题背景
设预定义了类A、B,在main函数中调用类A的方法func1,func1中传入装有类B中多个方法的函数的列表Lis,如果进行如下调用,会出现AttributeError问题(Lis中的各方法会调用类B中的self方法):
def func1(classBMethoedLis):
params = ...
methoedId = randint(len(classBMethoedLis))
a = classBMethoedLis[methoedId](params)
注:直接传入类B中的某个方法名,进行调用就不会报错,但是这里需求是必须要多个方法随机调用。
解决方法
引入python内置的functools包,即:
import functools
随后在初始化类A或函数调用时,进行如下类A的self属性初始化/修改即可:
Bmethoed为字符串时:
self.methoedLis = [functools.partial(getattr(class B, Bmethoed))
for Bmethoed in classBMethoedLis]
Bmethoed为不含括号的匿名方法时:
self.methoedLis = [functools.partial(Bmethoed) for Bmethoed in classBMethoedLis]