我只是在研究一个示例来帮助我了解 OOP 在 Python 中的工作原理。这是我正在使用的类(class):
class account(object):
def __init__(self,holder,number,balance,credit_line=1500):
self.holder=holder
self.number=number
self.balance=balance
self.credit_line=credit_line
def deposit(self,amount):
self.balance+=amount
def withdraw(self,amount):
if (self.balance-amount < -self.credit_line):
#coverage insufficient
return False
else:
self.balance-=amount
return True
def balance(self):
return self.balance
def transfer(self,target,amount):
if (self.balance-amount < -self.credit_line):
#coverage insufficient
return False
else:
self.balance-=amount
target.balance+=amount
return True
这是我用来测试它的驱动程序:
import account
john=account.account("John Doe","12345","1000.00")
res=john.balance()
print "%r" %res
john.deposit(1500)
res=john.balance()
print "%r" %res
当我尝试运行此命令时出现错误:
Traceback (most recent call last):
File "banker.py", line 4, in <module>
res=john.balance()
TypeError: 'str' object is not callable
有人知道这是为什么吗?
最佳答案
您正在掩盖对象的属性。
self.balance=balance
和
def balance(self):
Python 不区分 self.balance
数字和 self.balance
函数。最后分配的内容将被保留。为每个属性指定一个唯一的名称。
关于python - 了解错误 : 'str' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30716268/