[英]Understanding error: 'str' object is not callable
我只是在研究一个示例,以帮助我学习OOP如何在Python中工作。 这是我正在合作的课程:
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
函数。 最后分配的是坚持的。 给每个属性一个唯一的名称。
即使self.balance
在您的类中定义为方法,但在self.blance=balance
__init__
期间它也会被字符串替换。 因此,在这种情况下,当balance
是字符串"1000.00"
时,您调用john.balance()
时,它将返回非常有用的错误TypeError: 'str' object is not callable
。
建议:
balance
方法仅返回该值。 在当前示例中,确实不需要任何方法。 但是,如果您想开发它以在每次调用时做进一步的工作,那么这当然是可行的方法。 您不能为类的方法和属性使用相同的名称。 您不需要balance()
方法,并且通常python不需要使用getter和setter方法来访问属性。 Class_name.attribute_name
将返回属性的值
def balance(self):
return self.balance
已覆盖的功能balance
你的属性balance
。 您应该将属性重命名为例如self._balance
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.