如果速率隨時間變化,則必須使用時間相關函數進行建模。
這個功能如何確定給定的時間點或時間範圍右邊的數值是下一個步驟:
- 如果你硬編碼值到程序,你必須每次更改後更改程序。
- 如果將其放入數據庫中,則會有一個額外的數據庫查詢,但可以在「實施」中對其進行更改。
- 您還可以 - 在廣泛的程序中 - 讓程序從中央服務器加載正確的值並將其存儲在某個地方。
根據您所使用的解決方案,你可以做
def calculate_tax_for_year(self, income, year):
return _calculate_tax_for_year(self, income, tax_for_year(year)):
def tax_for_year(year): # solution 1
if year < 2010: return .2
if year < 2013: return .18
# etc.
def tax_for_year(year): # solution 2
with dbconn as cursor:
cursor.execute("SELECT rate FROM taxrate WHERE year == %s", year)
return cursor.fetch_one_row() # don't remember the syntax; something like this...
# solution 3:
def tax_for_year(year):
# just describing the steps:
with open("path/to/taxfile", "r") as f:
taxdata = f.read()
# parse table file, e. g. CSV
# find the right entry
return entry_matching_for_given_year
def update_tax_file():
import urllib
conn = urllib.urlopen("http://my.taxfile/url.csv")
# check if the file has changed since last check
# if so:
data = conn.read()
with open("path/to/taxfile", "w") as f:
f.write(data)
您能詳細介紹一下代碼示例(2,3)嗎? – Dominik
@Dominik我添加了一些代碼示例。 – glglgl