元类中用@property定义的类属性无法在继承类的实例中访问如何解决
问题原因
你遇到的问题是Python属性查找规则的正常表现:元类中定义的属性、方法包括装饰器生成的property,仅对类本身生效,类的实例查找属性时,只会遍历自身__dict__、所属类及父类的__dict__,不会访问元类的任何属性,所以实例找不到depth属性属于预期行为。
解决方案
你有两种可选的实现方式,都可以满足「类和实例都能访问该属性」的需求:
方案1:手动给类添加实例级property转发
给你的OtherClass补充一个同名的实例property,直接转发到类的属性即可,修改后完整代码如下:
class TopLevel(type): """ 定义类属性的元类 """ @property def depth(cls) -> int: return cls._depth class OtherClass: """ 后续绑定TopLevel元类的业务类 """ def __init__(self, var): self.var = var # 新增实例级property,转发到类的depth属性 @property def depth(self): return self.__class__.depth # 后绑定元类逻辑不变 OtherClass = TopLevel(OtherClass.__name__, OtherClass.__bases__, dict(OtherClass.__dict__)) OtherClass._depth = 3 # 测试 print(OtherClass.depth) # 输出3 otherclass = OtherClass(4) print(otherclass.depth) # 输出3
方案2:元类自动注入转发逻辑
如果你需要批量给多个后绑定元类的类添加该能力,可以直接修改元类的__new__方法,在创建类的时候自动注入实例级的转发property,不需要每个业务类手动加:
class TopLevel(type): """ 定义类属性的元类,自动注入实例访问能力 """ def __new__(cls, name, bases, attrs): # 自动给类添加实例级depth的转发逻辑 @property def depth(self): return self.__class__.depth attrs['depth'] = depth return super().__new__(cls, name, bases, attrs) @property def depth(cls) -> int: return cls._depth class OtherClass: """ 后续绑定TopLevel元类的业务类 """ def __init__(self, var): self.var = var # 后绑定元类逻辑不变 OtherClass = TopLevel(OtherClass.__name__, OtherClass.__bases__, dict(OtherClass.__dict__)) OtherClass._depth = 3 # 测试 print(OtherClass.depth) # 输出3 otherclass = OtherClass(4) print(otherclass.depth) # 输出3
两种方案都可以实现你的需求,方案1更灵活,方案2适合批量处理的场景。
内容的提问来源于stack exchange,提问作者pierre_j
相关产品推荐
相关产品推荐

