繁体   English   中英

理解错误:“ str”对象不可调用

[英]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

建议:

  1. 方法和属性使用不同的名称。
  2. 看来平衡是一个数字。 为什么将其作为字符串传递?
  3. 目前, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM