You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python子类如何更新/扩展继承的字典属性并解决属性设置报错

问题原因

报错核心原因是属性读写权限不匹配:

  • 你在Child2中用@property定义的information是只读属性:只实现了getter读方法,没有实现对应的setter写方法
  • 实例化Child2时,会执行父类Child1的__init__方法,其中的self.information={"TOKEN":"true"}是对information属性的赋值操作,会尝试调用该属性的setter方法,找不到可写的setter就会直接抛出AttributeError: can't set attribute
  • 除此之外原代码还有隐藏问题:就算绕过赋值报错,直接在property的getter中调用super().information,会因为属性查找顺序问题触发递归调用,最终导致栈溢出。
正确实现方案

修复需要做两处调整:一是给property补充对应的setter承接父类的赋值逻辑,二是用内部私有属性存储父类传入的属性值,避免递归问题。
修复后的可运行代码:

class MyBaseClass:
    information = {}
    
    def show_information(self):
        print(self.information)
        
        
class Child1(MyBaseClass):
    def __init__(self):
        super().__init__()
        self.information = {"TOKEN": "true"}
        
class Child2(Child1):
    def __init__(self):
        # 提前初始化内部存储变量,避免属性不存在报错
        self._parent_information = {}
        super().__init__()
    
    @property
    def information(self):
        # 合并自身新增字段和父类属性值
        current_info = {"IP": 198}
        current_info.update(self._parent_information)
        return current_info
    
    @information.setter
    def information(self, value):
        # 接收父类初始化时的赋值,存入内部私有属性
        self._parent_information = value


child2 = Child2()
child2.show_information()

运行代码输出结果为:

{'IP': 198, 'TOKEN': 'true'}

完全符合扩展父类同名属性取值的需求。

内容的提问来源于stack exchange,提问作者KZiovas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:03:19