我正在使用自定义数字类型,最好被认为是YearQuarter(即20141,20142,20143,20144,20151,20152,...),或者我标记为quarter_code
, q_code
简称。它的递增函数类似于:
def code_sum(q_code, n):
q_code_year, q_code_quarter = q_code // 10, q_code % 10
n_year, n_quarter = (n // 4), (n % 4 - 1)
quarters = q_code_quarter + n_quarter
years = q_code_year + n_year + quarters // 4
return years * 10 + quarters % 4 + 1
# code_sum(20141, 1) = 20142, code_sum(20144, 1) = 20151
# code_sum(20144, -1) = 20143, code_sum(20151, -1) = 20144
# NOTE: code_sum(20147, 0) = 20153
我想警告或提出不符合year*10 + number_of_quarters
格式的数字的例外情况。编写和调用check
函数很容易,但我想知道在许多不同的函数中使用check
时,不断调用quarter_codes
是否是最好的方法。 E.g。
def foo(qc1, qc2, qc3):
qc1, qc2, qc3 = check(qc1, qc2, qc3)
# do something
return bar
def foo2(qc, arg1, arg2) ...
qc = check(qc)
return 42
def fooN(qc1, qc2, arg1):
qc1, qc2 = check(qc1, qc2)
等等。这是一个简短的check
函数作为示例。
def check(*args):
checked = tuple()
for q_code in args:
if q_code % 10 > 4:
while q_code % 10 > 4:
q_code += 6
print('Number of quarters > 4. Using {}'.format(q_code))
checked += (q_code, )
else:
checked += (q_code, )
return checked[0] if len(checked) == 1 else checked
创建class YearQtr
似乎有点费力,尽管我可能完全错过了一些东西。我的问题真的可以归结为:我应该在多大程度上创建一个自定义数字类或类型?我该怎么做?
答案 0 :(得分:2)
我希望这可以帮到你
class QuarterCode(object):
"""docstring for QuarterCode"""
@property
def value(self):
return self.__value;
@value.setter
def value(self, value):
assert 1 <= value%10 <=4, "Number of quarters differs from {1,2,3,4}"
self.__value = value
def __init__(self, value):
self.value = value
def code_sum(self, n):
q_code_year, q_code_quarter = self.value // 10, self.value % 10
n_year, n_quarter = (n // 4), (n % 4 - 1)
quarters = q_code_quarter + n_quarter
years = q_code_year + n_year + quarters // 4
self.value = years * 10 + quarters % 4 + 1
您可以按如下方式使用此课程:
>>>q1 = QuarterCode(20142)
>>>q1.value
20142
>>>q1.code_sum(10)
20164
>>>q1.value = 20145
AssertionError: Number of quarters differs from {1,2,3,4}