简体   繁体   English

'int'对象在python中不可调用

[英]'int' object is not callable in python

I got this and I was expecting it to print 410 when I print x.withdraw(). 我得到了这个,我期望在我打印x.withdraw()时能打印410。

Kyle 12345 500
Traceback (most recent call last):
    File "bank.py", line 21, in <module>
        print x.withdraw()
TypeError: 'int' object is not callable

Here is my code: 这是我的代码:

class Bank:
    def __init__(self, name, id, balance, withdraw):
        self.name = name
        self.id = id
        self.balance = balance
        self.withdraw = withdraw
    def print_info(self):
        return "%s %d %d" % (self.name, self.id, self.balance)
    def withdraw(self):
        if self.withdraw > self.balance:
            return "ERROR: Not enough funds for this transfer"
        elif self.withdraw < self.balance and self.withdraw >= 0:
            self.balance = self.balace - self.withdraw
            return self.balance
        else:
            return "Not a legitimate amount of funds"

x = Bank("Kyle", 12345, 500, 90)
print x.print_info()
print x.withdraw()

Do I need to fix something within the class itself or is something wrong with my method calling? 我是否需要在类本身中修复某些问题,或者我的方法调用有问题?

You set an attribute on the instance with the same name: 您在实例上设置具有相同名称的属性:

self.withdraw = withdraw

It is that attribute you are trying to call now, not the method. 您正在尝试调用的是该属性,而不是方法。 Python doesn't differentiate between methods and attributes, they do not live in separate namespaces. Python不会区分方法和属性,它们不存在于单独的命名空间中。

Use a different name for the attribute; 为属性使用其他名称; withdrawn (past tense of to withdraw) springs to mind as a better attribute name: withdrawn (要撤消的过去时)作为更好的属性名称浮现在脑海:

class Bank:
    def __init__(self, name, id, balance, withdrawn):
        self.name = name
        self.id = id
        self.balance = balance
        self.withdrawn = withdrawn
    def print_info(self):
        return "%s %d %d" % (self.name, self.id, self.balance)
    def withdraw(self):
        if self.withdrawn > self.balance:
            return "ERROR: Not enough funds for this transfer"
        elif self.withdrawn < self.balance and self.withdrawn >= 0:
            self.balance = self.balance - self.withdrawn
            return self.balance
        else:
            return "Not a legitimate amount of funds"

(I also corrected a typo; you used balace in one location where you meant to use balance ). (我也纠正了一个错字;您在打算使用balance位置使用了balace )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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