Python:使用自定义数字类或类型

标签 python

我正在使用自定义数字类型,最好将其视为 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 函数很容易,但我想知道在许多不同的地方使用 quarter_codes 时,不断调用 check 是否是最好的方法职能。例如

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 似乎有点费力,但也许我在这里完全遗漏了一些东西。我的问题实际上归结为:我应该在多大程度上创建自定义数字类或类型?我该怎么做?

最佳答案

希望对你有帮助

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}

关于Python:使用自定义数字类或类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21996094/

相关文章:

python - time.sleep 使图片循环不显示

python - Plotly OHLC 和 Plotly Candlestick 图表之间有区别吗?

python - 增加 tkSimpleDialog 窗口大小

python - 在 emacs 中以 comint 模式执行带有参数的 python 脚本

python - 从 Teradata 提取几百万条记录到 Python (pandas)

python - Python 使用 Socket 发送多个文件

在 Mac 上安装 requests 模块时 Python 2.7 崩溃

python - 运行 flask 应用程序时将数据传递给配置?

python - 序列化程序在 Javascript 中添加了不必要的字段

python - 在 Django 中将请求对象从 View 传递到表单