python 为什么存款后余额为零?

f45qwnt8  于 2023-02-18  发布在  Python
关注(0)|答案(2)|浏览(126)

我创建了这个简单的取款机和存款机,并使用类方法进行存款,但似乎有一些错误,因为我期望存款方法的返回值为= 20,500,但它的值为= None,所以这里的问题是什么?我的代码中有任何错误吗?

print("Hello !!! Welcome to Deposit & Withdrawal Machine")

class Account:

    withDrawalAmount = 0 
    depositAmnt = 0 
    
    
    def __init__(self , ID = 0 ,  balance = 100 , annual_interest_rate = 0):
        self.__ID = ID
        self.__balance = balance
        self.__annual_interest_rate = annual_interest_rate

    #setters
    def setId (self , ID):
         self.__ID = ID

    def setBal (self , Bal):
         self.__balance = Bal

    def setAnnualInterestRate(self , annualIntrstRate):
         self.__annual_interest_rate = annualIntrstRate

    #getters
    def getId (self):
        return self.__ID

    def getBal (self):
        return self.__balance

    def getAnnualIntrstRate(self):
        return self.__annual_interest_rate

    #special getters 
    def getMonthlyInterestRate(self):
        self.annual_rate = self.__annual_interest_rate/100
        self.monthly_rate = self.annual_rate / 12
        return self.monthly_rate

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

    #other methods

    def withdraw (self , withDrawalAmount):
        if self.__balance >= self.withDrawalAmount:
            self.__balance = self.__balance - self.withDrawalAmount 
            return self.__balance


    def deposit (self , depositAmnt ):
        if self.depositAmnt >=  1 :
            self.__balance = self.__balance + self.depositAmnt
            return self.__balance
        

client001 = Account (1122 , 20000 , 4.5)

print ("Your Balance After withdrawal is : ",client001.withdraw(2500))
print ("Your Balance After deposit is : ", client001.deposit(3000))
print ("Your Account ID is : " , client001.getId())
print ("Your Current Balance is : " , client001.getBal())
print ("Your Monthly Intrst Rate is : " , client001.getMonthlyInterestRate())
print ("Your Monthly intrst is : " , client001.getMonthlyInterest())
busg9geu

busg9geu1#

def deposit (self , depositAmnt ):
    if self.depositAmnt >=  1 :
        self.__balance = self.__balance + self.depositAmnt
        return self.__balance

存入的金额是depositAmnt,而不是self.depositAmnt
if条件为false,因此函数不返回任何内容,因此默认情况下返回None

qmelpv7a

qmelpv7a2#

正如John已经提到的,要纠正这一点,需要在if语句中使用变量depositAmnt

def deposit (self , depositAmnt ):
        if depositAmnt >=  1 :
            self.__balance = self.__balance + depositAmnt
            return self.__balance

现在,类的属性-withDrawalAmountdepositAmnt没有任何用处(因为您将它们作为参数输入到函数depositwithdraw中)。
您还应该将withdraw函数更改为:

def withdraw (self , withDrawalAmount):
        if self.__balance >= withDrawalAmount:
            self.__balance = self.__balance - withDrawalAmount 
            return self.__balance

相关问题