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

Python类中自定义方法返回指定属性遇异常问题求助

问题解决

你的代码存在两个关键问题,直接导致了异常和不符合预期的返回结果:

1. balance方法的无限递归错误

你在balance方法中写了return self.balance,这里的self.balance指向的是方法本身,每次调用都会触发方法的重复调用,最终会抛出递归深度超出的异常。正确写法应该返回实例的value属性,也就是self.value。

2. 方法调用的语法问题

如果调用方法时没加括号(比如写acc.owner而不是acc.owner()),得到的会是方法对象的内存地址,必须加上括号才能执行方法并获取返回值。

修正后的完整代码

class Account():
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def __str__(self):
        return f'Account owner: {self.name}\nAccount balance: ${self.value}'

    def owner(self):
        return self.name

    def balance(self):
        return self.value  # 修正为返回实例的value属性

调用示例

acc = Account("Alice", 100)
print(acc.owner())  # 输出 Alice
print(acc.balance())  # 输出 100
print(acc)  # 输出__str__定义的账户信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:45:59