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

Python子类继承父类property属性遇递归超限问题求解决方案

问题解决:递归错误与Property继承修正

错误原因分析

  1. 父类Property的递归死循环:
    父类Account的setter方法中,self.account_type = new_acount_value会触发自身的setter调用,形成无限递归,最终导致RecursionError。同时还存在拼写错误:@property装饰的方法名是acount_type(少写了字母c),但setter装饰的是account_type,导致getter和setter不匹配。
  2. 子类继承Property的方式错误:
    子类Customer不必要地直接调用property底层的__get__和__set__方法,这种写法既复杂又不符合Python继承property的常规方式,且父类本身的property存在错误,进一步引发问题。
  3. 字典快照的静态特性:
    原调用代码中,details是create_account()返回的静态字典,修改对象的account_type后,字典内的旧值不会自动更新,这也是无法得到期望输出的原因之一。

修正后的代码实现

父类Account(修复递归与拼写错误)

class Account():
    def __init__(self, account_type, id, name):
        # 使用私有变量存储账户类型,避免触发setter递归
        self._account_type = account_type
        self.id = id
        self.name = name

    def create_account(self) -> dict:
        account_details = {}
        # 通过property的getter获取最新值
        account_details['acnt_type'] = self.account_type
        account_details['id'] = self.id
        account_details['name'] = self.name
        return account_details

    @property  
    def account_type(self):
        return self._account_type

    @account_type.setter  
    def account_type(self, new_account_value):
        # 直接赋值给私有变量,不会触发递归
        self._account_type = new_account_value

子类Customer(简化继承)

子类无需重写property,直接继承父类的实现即可:

class Customer(Account):
    def __init__(self, account_type, id, name):
        super().__init__(account_type, id, name)

修正后的调用代码

由于字典是静态快照,修改属性后需要重新调用create_account()获取最新的字典:

acnt_type, id, name = ('savings', '101','Umesh')
obj = Customer(account_type=acnt_type, id=id, name=name)

print("Initial run")
details = obj.create_account()
print(details)

print("-- Updating account type")
obj.account_type = 'Fixed'
# 重新获取最新的账户详情
details = obj.create_account()
print(details)

运行结果

Initial run
{'acnt_type': 'savings', 'id': '101', 'name': 'Umesh'}

-- Updating account type
{'acnt_type': 'Fixed', 'id': '101', 'name': 'Umesh'}

总结

  • 父类实现property时,必须使用私有变量存储值,避免赋值时触发setter递归。
  • 子类继承父类property无需复杂操作,直接继承即可,如需扩展逻辑,可通过super()调用父类的property方法。
  • 字典是静态数据结构,若需要获取对象属性的最新值,需重新生成字典或使用动态数据结构(如自定义类)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:55:07