python:将数据传递给类构造函数
我有一个Account类,它有3个数据字段(id、余额、年利率)。如果我只是打印出余额,或者调用一些函数来获取月利息,等等,一切都正常。。。 但是我也需要展示存款和取款的结果,这就是我被困的地方,我猜我必须做这样的事情python:将数据传递给类构造函数,python,python-3.x,Python,Python 3.x,我有一个Account类,它有3个数据字段(id、余额、年利率)。如果我只是打印出余额,或者调用一些函数来获取月利息,等等,一切都正常。。。 但是我也需要展示存款和取款的结果,这就是我被困的地方,我猜我必须做这样的事情 ending_balance = account.withdraw(2500) + account.deposit(3000) 但我不确定如何将期末余额传递给账户构建者,以便利率根据新的余额进行调整 class Account: def __init__(self,
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()
因此,您的
取款
和存款
必须更新实际字段,以强制使用您的self。设置余额
或直接设置余额。余额=新余额:
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)
这是关于主功能中的逻辑
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)
将提供正确的期末余额。在取款和存款方法中更新
self.\u余额,而不是return
ing值