Python Account类二次调用withdraw报int不可调用TypeError
错误原因
核心问题是实例属性与类方法命名冲突,同时代码存在基础缩进语法错误:
- 缩进错误:类定义下的
__init__方法没有保持正确的层级缩进,Python要求类下的方法必须相对class关键字缩进4个空格,否则会直接抛出语法错误。 - 命名冲突:你在
withdraw方法内写了self.withdraw = withdraw,第一次调用该方法时,Python会先从类中找到withdraw函数正常执行,但执行到这行赋值语句时,会给当前实例绑定一个整数类型的withdraw属性(即你传入的取款金额),直接覆盖了类层面定义的withdraw方法。第二次调用实例.withdraw()时,Python优先找到实例上的整数属性,整数无法被调用,就会抛出TypeError: 'int' object is not callable异常。 - 同名问题在
deposit方法中同样存在:self.deposit = deposit这行代码会在第一次调用存款方法后覆盖deposit方法,后续再调用存款方法也会触发完全相同的错误。
修正后代码
class Account: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def __str__(self): return f"the account holder is {self.owner} \nand the balance is {self.balance}" def deposit(self, amount): self.balance += amount print("deposit accepted") def withdraw(self, amount): if self.balance >= amount: self.balance -= amount print("money withdrawn") else: print("Funds Unavailable!")
注意要点
Python的属性查找遵循「实例属性优先级高于类属性/方法」的规则:当你通过
self.属性名 = 值给实例绑定属性时,如果属性名和类下定义的方法重名,就会直接遮蔽原有方法。编写类代码时要注意:方法的形参名、实例绑定的属性名都不要和方法本身重名,避免出现覆盖问题。
内容的提问来源于stack exchange,提问作者shivam tuli
相关产品推荐
相关产品推荐

