如何在Python父类中修改__getattribute__并支持子类扩展特殊属性?
解决Python中__getattribute__与specialAttrs的递归问题
问题根源
你遇到的递归错误,本质是在重写的__getattribute__中访问self.specialAttrs时,会再次触发当前类的__getattribute__调用——因为所有属性访问(包括@property装饰的属性)都会经过__getattribute__,最终形成无限递归循环。
解决方案
要打破递归,需要在__getattribute__内部绕过自身的逻辑,直接调用最底层的属性获取方法来拿到specialAttrs的值。可以通过object.__getattribute__实现,它不会触发我们重写的逻辑,是Python属性查找的最基础实现。
修改后的父类代码如下:
class Parent: def __init__(self): self.parentAttr = "some string" @property def specialAttrs(self): return {"parentAttr"} def __getattribute__(self, attr: str): # 直接调用object的__getattribute__获取specialAttrs,避免递归 special_attrs = object.__getattribute__(self, 'specialAttrs') if attr in special_attrs: # 用super()获取原始属性值(比直接访问__dict__更通用,支持@property等场景) original_value = super().__getattribute__(attr) return "SPECIAL! " + original_value else: return super().__getattribute__(attr)
子类扩展验证
子类只需重写specialAttrs属性即可扩展特殊处理的属性列表,无需修改__getattribute__:
class Son(Parent): def __init__(self): self.sonAttr = "other string" super().__init__() @property def specialAttrs(self): return super().specialAttrs.union({"sonAttr"}) # 测试 son = Son() print(son.parentAttr) # 输出:SPECIAL! some string print(son.sonAttr) # 输出:SPECIAL! other string
关键说明
- 使用
object.__getattribute__(self, 'specialAttrs')直接获取属性,跳过当前重写的__getattribute__,彻底避免递归。 - 用
super().__getattribute__(attr)获取原始属性值,比直接访问self.__dict__[attr]更通用——即使属性是@property或类属性,也能正确获取。
内容的提问来源于stack exchange,提问作者Virtualvikings
相关产品推荐
相关产品推荐

