简体   繁体   English

Python类中两个对象的比较

[英]Comparison of the two objects in Python class

There is a code in which the broken version on major, minor, build, revision 在其中的代码中,主要版本,次要版本,内部版本和修订版本上的损坏版本

class VersionComparatorException(Exception):
    pass


class VersionParseException(Exception):
    pass


class Version(object):

    def __init__(self, version, major=0):
        self.major = major
        self.version = version
        ver = version.split('.')
        new_list = [re.sub('\D+', '', i) for i in ver]

        while len(new_list) < 4:
            new_list.append('0')
        print(new_list)
        major = new_list[0]
        minor = new_list[1]
        build = new_list[2]
        revision = new_list[3]
        for i in new_list:
            if len(i)==0:
                raise VersionParseException()


    def __lt__(self, test):
        return self.version < test.version

    def __eq__(self, test):
        return self.version == test.version

    def __ne__(self, test):
        return self.version != test.version

print(Version('6.4.2') < Version ('5.5hh.5'))

Compare Version can only Version How to realize that when compared to the following form threw out VersionComparatorException 比较版本只能显示版本如何实现与以下形式相比时抛出了VersionComparatorException

Version("1.0") == 1
Version("2.0") == "2.0"
Version("3.1.2") < [3, 1, 2]
Version("1.5.5") > dict()

You have to add following check: 您必须添加以下检查:

if not isinstance(test, Version):
    raise VersionComparatorException()

in each compare method or in some helper function. 在每个比较方法或一些辅助函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM