Python 2.7中如何检测派生类是否重赋值了实例属性
Python 2.7 中检测派生类重赋值属性的实现方法
核心前提
仅靠构造完成后的实例状态无法实现检测:
- 不管是父类
A.__init__中的self.a = 1,还是子类B.__init__中的self.a = 1,本质都是直接修改实例__dict__字典中键为a的条目,两次操作没有留下任何赋值历史痕迹,最终vars(obj_b)只会输出一个a:1的条目,无法从最终状态反推赋值的触发位置。 - 要实现检测,必须在属性赋值的流程中提前埋点追踪。
方案1:自定义带追踪功能的描述符(可靠性最高)
核心原理是将需要追踪的属性替换为自定义描述符,描述符每次响应赋值操作时,会通过栈帧回溯定位赋值操作所属的类,记录赋值的来源路径。
适配Python 2.7的实现代码:
import inspect class TracedAttribute(object): def __init__(self, attr_name): self.attr_name = attr_name self.assign_sources = [] # 记录所有触发该属性赋值的类 def __get__(self, instance, owner_cls): if not instance: return self return instance.__dict__.get(self.attr_name) def __set__(self, instance, value): # 回溯栈帧,定位当前赋值操作的触发类 current_frame = inspect.currentframe().f_back while current_frame: if 'self' in current_frame.f_locals: trigger_cls = type(current_frame.f_locals['self']) if trigger_cls not in self.assign_sources: self.assign_sources.append(trigger_cls) # 栈帧追溯到构造函数入口即停止,避免无效遍历 if current_frame.f_code.co_name == '__init__': break current_frame = current_frame.f_back # 执行实际的属性赋值 instance.__dict__[self.attr_name] = value
改造原有类结构(Python 2.7 的描述符仅对继承object的新式类生效):
class A(object): a = TracedAttribute('a') b = TracedAttribute('b') def __init__(self): self.a = 1 self.b = 3 class B(A): def __init__(self): A.__init__(self) self.a = 1 obj_b = B() # 检测逻辑:只要类B在a的赋值来源列表中,即说明a在B中被重赋值 is_reassigned = B in B.a.assign_sources # 执行结果为True
方案2:构造过程动态插桩(零侵入修改原有类)
如果不想改造原有类的结构、无法提前为属性添加描述符,可以在实例构造的过程中临时替换类的__setattr__方法,在赋值发生时动态追踪来源。代码完全兼容Python 2.7语法:
import inspect def check_attr_reassigned_in_subclass(sub_cls, target_attr): original_setattr = sub_cls.__setattr__ # 用可变列表存储标记,适配Python 2.7无nonlocal关键字的限制 reassigned_flag = [False] def patched_setattr(instance, attr, value): if attr == target_attr: # 回溯栈帧定位赋值来源 frame = inspect.currentframe().f_back while frame: # 确认赋值操作是子类自身的构造函数触发的 if frame.f_code.co_name == '__init__' and type(frame.f_locals.get('self')) is sub_cls: reassigned_flag[0] = True break frame = frame.f_back original_setattr(instance, attr, value) # 临时替换setattr完成构造检测 sub_cls.__setattr__ = patched_setattr test_instance = sub_cls() # 恢复原方法,避免影响后续类的正常逻辑 sub_cls.__setattr__ = original_setattr return reassigned_flag[0] # 调用检测 check_result = check_attr_reassigned_in_subclass(B, 'a') # 执行结果为True
常见误区
不要尝试通过对比实例和父类实例的__dict__做检测,这种方法只能识别子类新增的独有属性,完全无法区分“子类和父类给同名属性赋了相同值”的场景。
内容的提问来源于stack exchange,提问作者james
相关产品推荐
相关产品推荐

