TypeError:不支持的操作数类型 - :' float'和'方法'

时间:2015-04-28 23:38:00

标签: python typeerror

所以大家好,我在阅读了类和对象之后尝试用Python练习一些练习,其中一个练习是创建一个帐户类,并编写方法来提取和存入账户。每次运行它时,我都会收到一个TypeError,告诉我Floats和Methods不支持该操作数。我觉得我很近但却遗漏了一些非常明显的东西。谁能让我知道我做错了什么以及如何解决这个问题?

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()

1 个答案:

答案 0 :(得分: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