我必须创建一个具有以下功能的银行账户类:存款、取款、获取余额;所有那些初学者的东西。一切都很简单,我完成了没问题。但是,有一个名为 Interest 的函数接受了一个 interest_rate ,我遇到了很多麻烦。解释一下,这个功能应该每月只根据用户的请求增加一次兴趣到银行账户的余额。因此,假设我决定在今天(10 月 13 日)将 5% 的利息添加到我的余额中。该函数将执行并吐出我的新余额。然后假设我想在第二天(10 月 14 日)添加 10% 的利息,该函数不会执行,并且会吐出类似“无法在 11 月 1 日之前添加利息”之类的内容,这是下个月的第一天。在 11 月 1 日,如果我尝试添加 10% 的利息,我会成功,然后如果在 11 月 2 日我再次尝试添加利息,它会说“直到 12 月 1 日才能添加利息”等等。我很难过。下面是我编写的代码,但它不仅会执行,因为日期总是提前一个月,而且它也总是会增加余额的兴趣。
这是我到目前为止所拥有的,但它是一团糟。有人对我应该做什么有任何提示吗?我知道它不像作业中应该的那样在函数内部,但我想我会先弄清楚程序的主要图片,然后再担心将其合并到我班级的其余部分中。
from datetime import *
from dateutil.relativedelta import *
rate = 0.10
balance = 1000.00 # i just made up a number for the sake of the code but the
# balance would come from the class itself
balancewInterest = rate*balance
print(balancewInterest)
# this is where I'm having the most trouble
todayDate = date.today()
print(todayDate)
todayDay = todayDate.day
todayMonth = todayDate.month
if todayDay == 1: # if it's the first of the month, just change the month
# not the day
nextMonth = todayDate + relativedelta(months=+1)
else: # if not the 1st of the month, change day to 1, and add month
nextMonth = todayDate + relativedelta(months=+1, days=-(todayDay-1))
print(nextMonth)
difference = (todayDate - nextMonth)
print(difference.days)
if todayDate >= nextMonth: # add interest only when it's the first of the next
# month or greater
interestPaid = rate*balance
print(interestPaid)
else:
print("You can add interest again in " + str(abs(difference.days)) \
+ " days.")