python - 了解错误 : 'str' object is not callable

标签 python

我只是在研究一个示例来帮助我了解 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/

相关文章:

python - 将 str 添加到每行值的开头

python - 如何将多维列表插入到sqlite db

python - 保存sklearn交叉验证对象

python - flask 测试 : Test App Request?

列表的 Python 拆分

python - openpyxl:从 Excel 中丢失精度读数 float ?

Python SQLAlchemy : Data source name not found and no default driver specified

python - 限制正则​​表达式中的位数

python - 使用其他列值的串联来过滤文本列上的 Pandas DataFrame

python - 使用 plotly python 导出 pdf