我的帐户类有3个数据字段(id,余额,年利率)。如果我只是打印出余额是什么,或者调用一些功能来获得每月的兴趣等等,一切都运作良好...... 但我需要显示存款和取款的结果,这就是我被困住的地方,我猜我必须做这样的事情
ending_balance = account.withdraw(2500) + account.deposit(3000)
但是我不确定如何取得期末余额并将其传递给账户构造函数,以便利率根据新余额进行调整。
class Account:
def __init__(self, id, balance, annual_interest_rate):
self.__id = id
self.__balance = balance
self.__annual_interest_rate = annual_interest_rate
def withdraw(self, withdrawal):
return float(self.get_balance() - withdrawal)
def deposit(self, deposit):
return float(self.get_balance() + deposit)
def main():
account = Account(1122, 20000, 4.5)
ending_balance = account.withdraw(2500) + account.deposit(3000)
if __name__ == '__main__':
main()
答案 0 :(得分:2)
因此,您的withdraw
和deposit
必须更新实际字段,强制使用您的self.set_balance
或直接self.__balance = newbalance
:
def withdraw(self, withdrawal):
self.set_balance(self.get_balance() - withdrawal)
return float(self.get_balance() - withdrawal)
def deposit(self, deposit):
self.set_balance(self.get_balance() + deposit)
return float(self.get_balance() + deposit)
答案 1 :(得分:1)
这是关于主函数中的逻辑。
account = Account(1122, 20000, 4.5)
ending_balance = account.withdraw(2500) + account.deposit(3000)
上述行未提供期末余额。
进行这些更改,
def withdraw(self, withdrawal):
self.__balance = self.get_balance() - withdrawal
return float(self.__balance)
def deposit(self, deposit):
self.__balance = self.get_balance() - deposit
return float(self.__balance)
并在主屏幕中调用它,
account.withdraw(2500)
ending_balance = account.deposit(3000)
将提供正确的期末余额。