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
相关产品推荐
相关产品推荐

