如何修饰从元组继承的所有比较方法



问题

版本被表示为字符串,并在许多地方进行比较。但是随后";5.10";CCD_ 1";5.2〃;由于ASCII比较

解决方案

将其更改为tuple,然后进行比较。由于比较是在多个地方进行的,我想到了有一个从tuple继承的自定义类,并自己处理比较

建议的代码

class Version(tuple):
def __new__(self, v1):
if not isinstance(v1, tuple):
v1 = tuple(map(lambda x: int(x), v1.split('.')))
return tuple.__new__(Version, v1)
def __lt__(self, other):
if not isinstance(other, tuple):
other = tuple(map(lambda x: int(x), other.split('.')))
return super().__lt__(other)
def __repr__(self):
return '.'.join(str(x) for x in self)

到目前为止,这是我想出的代码,它似乎适用于以下情况:

v1 = Version("5.10")
print(v1 < "5.2")

我的问题是,我如何才能避免对所有其他方法__le____gt__等做同样的事情。

应该有一种更像蟒蛇的方法来处理other参数并将其转换为tuple,然后调用基类对应的方法

根据注释中的建议,将继承更改为组合并使用total_ordering

from functools import total_ordering
@total_ordering
class Version():
def __init__(self, v1):
self.v1 = tuple(map(lambda x: int(x), v1.split('.')))
def __eq__(self, other):
if not isinstance(other, tuple):
other = tuple(map(lambda x: int(x), other.split('.')))
return self.v1 == other
def __lt__(self, other):
if not isinstance(other, tuple):
other = tuple(map(lambda x: int(x), other.split('.')))
return self.v1 < other
def __repr__(self):
return '.'.join(str(x) for x in self.v1)

最新更新