1

我正在做一些与 Python 中的类有关的作业。但我被困在一个我不太明白的地方。

它告诉我:

--> 编写一个名为withdraw()从帐户中提取指定金额的方法。帐户中的余额会减少方法参数中指定的金额。仅当参数中指定的金额小于或等于 balance 时,才应减少余额

这是我的程序

class Account:
    def __init__(self,id=0):
        self.__id = id
        self.__balance = 0
        self.__annualInterestRate = 0

    def getid(self):
        return self.__id

    def getbalance(self):
        return self.__balance

    def getannualInterestRate(self):
        return self.__getannualInterestRate

    def setid(self):
        self.__id = id

    def setbalance(self):
        self.__balance = balance

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


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

然后我将不得不:

def withdraw():
   # I don't know what to do here
4

2 回答 2

3

您需要传递隐含的self参数(此处和其他一些方法)和一个amount

def withdraw(self, amount):
   # subtract amount from self.__balance

return在继续上课之前,您还应该阅读声明。

于 2013-04-04T09:16:33.900 回答
2

您的代码中有各种错误。我修改class A为一个可执行类,包括withdraw函数

class Account:
    def __init__(self,id=0):
        self.__id = id
        self.__balance = 0
        self.__annualInterestRate = 0

    def getid(self):
        return self.__id

    def getbalance(self):
        return self.__balance

    def getannualInterestRate(self):
        return self.__annualInterestRate

    def setid(self,id):
        self.__id = id

    def setbalance(self, balance):
        self.__balance = balance

    def setannualInterestRate(self, rate):
        self.__annualInterestRate = rate

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

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

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
            return True
        else:
            return False
于 2013-04-04T09:25:31.317 回答