问题背景
设预定义了类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]
文章介绍了在Python编程中遇到的问题,当在类A的func1方法中尝试通过方法列表调用类B的self方法时,会导致AttributeError。解决方案是利用functools.partial将类B的方法转换为可调用对象,确保在没有实例化类B的情况下也能正确执行。这涉及到对类方法、self属性以及functools模块的理解和应用。
1188

被折叠的 条评论
为什么被折叠?



