【问题标题】:TypeError: unsupported operand type(s) for -: 'float' and 'method'TypeError: 不支持的操作数类型 -: 'float' 和 'method'
【发布时间】:2015-04-29 07:40:01
【问题描述】:

所以伙计们,在阅读了有关类和对象的内容后,我正在尝试在 Python 中进行一些练习,其中一个练习是创建一个 Account 类并编写方法来提取和存入帐户中的钱。每次我运行它时,我都会收到一个 TypeError,告诉我浮点数和方法不支持该操作数。我觉得我很接近,但错过了一些非常明显的东西。谁能告诉我我做错了什么以及如何解决这个问题?

class Account:
    def __init__(account, id, balance, rate):
        account.__id = id
        account.__balance = float(balance)
        account.__annualInterestRate = float(rate)

    def getMonthlyInterestRate(account):
        return (account.__annualInterestRate/12)
    def getMonthlyInterest(account):
        return account.__balance*(account.__annualInterestRate/12)   
    def getId(account):
        return account.__id
    def getBalance(account):
        return account.__balance
    def withdraw(account, balance):
        return (account.__balance) - (account.withdraw)
    def deposit(account, balance):
        return (account.__balance) + (account.deposit)

def main():
    account = Account(1122, 20000, 4.5)
    account.withdraw(2500)
    account.deposit(3000)
    print("ID is " + str(account.getId()))
    print("Balance is " + str(account.getBalance()))
    print("Monthly interest rate is" + str(account.getMonthlyInterestRate()))
    print("Monthly interest is " + str(account.getMonthlyInterest()))

main()

【问题讨论】:

  • account.withdraw 是一种方法。除非你向它传递一个参数,否则它的行为就不会像一个数字。

标签: python typeerror


【解决方案1】:

这个:

def withdraw(account, balance):
    return (account.__balance) - (account.withdraw)

应该是这样的:

def withdraw(self, amount):
    self.__balance -= amount

在 Python 中,我们总是将方法中的类称为 self

将此应用于课堂的其余部分并清理一些内容:

class Account:
    def __init__(self, id, balance, rate):
        self.id = id
        self.balance = float(balance)
        self.annualInterestRate = float(rate)

    def getMonthlyInterestRate(self):
        return self.annualInterestRate / 12

    def getMonthlyInterest(self):
        return self.balance * self.getMonthlyInterestRate()

    def getId(self):
        return self.id

    def getBalance(self):
        return self.balance

    def withdraw(self, amount):
        self.balance -= amount

    def deposit(self, amount):
        self.balance += amount

【讨论】:

  • 老兄,非常感谢。那行得通。感谢您的澄清。
  • @jbar0787 如果我的回答解决了您的问题,您可以单击旁边的复选标记将您的问题标记为已解决。
  • 我会的。需要几分钟才能让您这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 2018-10-30
  • 2014-03-28
  • 2018-06-20
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多