了解错误:' str'对象不可调用

时间:2015-06-08 18:16:39

标签: python

我正在编写一个示例来帮助我了解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

任何人都知道为什么会这样?

4 个答案:

答案 0 :(得分:2)

您正在屏蔽对象的属性。

self.balance=balance

def balance(self):

Python不区分self.balance数字和self.balance函数。无论最后分配的是什么,坚持。为每个属性指定一个唯一的名称。

答案 1 :(得分:1)

即使self.balance被定义为您班级中的某个方法,但在__init__ self.blance=balance期间,它会被替换为字符串。因此,当您在john.balance()为字符串balance的情况下调用"1000.00"时,会返回非常有用的错误TypeError: 'str' object is not callable

建议:

  1. 为方法和属性使用不同的名称。
  2. 看起来平衡是一个数字。为什么把它作为字符串传递?
  3. balance方法当前只返回值。实际上,在当前示例中不需要方法。但是如果你想开发它来为每次通话做更多的事情,当然这是要走的路。

答案 2 :(得分:0)

您不能为类的方法和属性指定相同的名称。您不需要balance()方法,并且通常python不使用getter和setter方法来访问属性。 Class_name.attribute_name将返回您的属性值

def balance(self):
        return self.balance

答案 3 :(得分:0)

您已使用属性balance覆盖了您的函数self._balance。您应该将属性重命名为例如 T�vez & Messi: Argentine showdown

相关问题