长期稳定但会随时间变化的变量的设计模式是什么?假设2015年和2016年的所得税税率为18%,从2017年1月1日起将为20%。
INCOME_TAX = 0.18
def _calculate_tax(self, income, tax=INCOME_TAX):
return income*tax
当INCOME_TAX在2017年更改为0.2时,前几年的向后兼容性将被破坏。我认为将这个变量放入数据库中以允许在管理面板中对其进行某种修改可能是一个好主意,但是这样做必须有一些行业标准或良好实践。
如果速率随时间变化,则必须使用与时间有关的函数对其进行建模。
下一步是如何在给定的时间点或时间范围内确定正确的值:
根据您使用的解决方案,您可以执行
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句