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

Python中为何我的Calculator对象不存在current属性?

问题解决:AttributeError: 'Calculator' object has no attribute 'current'

问题根源在构造函数的命名上——Python类的构造函数必须是__init__(前后各两个下划线),你写成了_init_(单个下划线),导致创建Calculator实例时这个方法没被当作构造函数执行,self.current压根没被初始化,调用add方法自然会报找不到属性的错误。

修正后的代码:

class Calculator(object):
    def __init__(self):  # 修正为前后各两个下划线
        self.current = 0
    def add(self, amount):
        self.current += amount
    def sub(self, amount):
        self.current -= amount
    def getCurrent(self):
        return self.current

测试调用代码验证:

c = Calculator()
c.add(2)
print(c.getCurrent())  # 输出2,正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:29:53