python 版本号比较 重载运算符

# -*- coding: utf-8 -*-


class VersionNum(object):
    """
    版本号比较
    默认版本以“.”分割,各位版本位数不超过3
    例一:
        235.458.95 由“.”分割版本,235、458、95都不能大于999
        如果有版本要超过3位,需指定max_digit,但注意比较时,两个对比的max_digit必须相等!
    例二:
        if VersionNum('1.20.3') > VersionNum('1.9.3'): ...
    """
    def __init__(self, version, delimiter='.', max_digit=3):
        v_num = 0
        v_list = version.split(delimiter)
        for i, num in enumerate(v_list[-1::-1]):
            if len(num) > max_digit:
                raise ValueError('version can not greater than max_digit')
            v_num += int(num) * (10 ** (i*max_digit))
        self.max_digit = max_digit
        self.data = v_num

    def __repr__(self):
        """
        自我描述
        """
        return "VersionNum(%d)" % self.data

    def __eq__(self, other):
        self.check_max_digit(other)
        return self.data == other.data

    def __ne__(self, other):
        self.check_max_digit(other)
        return self.data != other.data

    def __lt__(self, other):
        self.check_max_digit(other)
        return self.data < other.data

    def __le__(self, other):
        self.check_max_digit(other)
        return self.data <= other.data

    def __gt__(self, other):
        self.check_max_digit(other)
        return self.data > other.data

    def __ge__(self, other):
        self.check_max_digit(other)
        return self.data >= other.data

    def check_max_digit(self, other):
        if self.max_digit != other.max_digit:
            raise ValueError('The max_digit of the two versions of the comparison should be equal')

 

posted @ 2019-08-06 18:36  aaron_agu  阅读(193)  评论(0编辑  收藏  举报