为Dataclass方法添加装饰器后字段初始化异常问题排查
图像旋转渲染错误分析与修复
问题现象
为EntityZombie类的live方法添加activated_range装饰器后,执行图像旋转渲染时触发TypeError: must be real number, not Field错误。此时父类Rotatable中定义的rotation字段未被初始化为默认值0.0,而是保留了dataclasses.Field对象;即使手动绑定装饰器也会触发错误,偶尔部分实例暂时正常但最终仍会崩溃。
根因
装饰器未使用functools.wraps保留原方法的元数据,导致Python的dataclass机制在处理类定义时,误将被装饰后的live方法识别为类字段进行处理,干扰了父类Rotatable中rotation字段的默认初始化流程,使得该字段未被正确赋值为默认数值。
修复方案
修改activated_range装饰器,为内部包装函数添加@functools.wraps(method)装饰,保留原方法的元信息,避免dataclass误判:
import functools def activated_range(activate_distance: float): def decorator(method): @functools.wraps(method) def new_func(instance, game): if instance.player_distance(game.player) > activate_distance: return method(instance, game) return new_func return decorator
验证说明
添加@functools.wraps(method)后,dataclass可正确识别live为类方法,不再干扰父类字段的初始化逻辑,rotation字段会被自动设置为0.0,图像旋转时的类型错误即可消除。
内容的提问来源于stack exchange,提问作者Eric Jin
相关产品推荐
相关产品推荐

