Mark Mark - 28 days ago 4
Python Question

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

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

Answer

You have to add following check:

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

in each compare method or in some helper function.

Comments