如果我有一个我想编写自定义比较函数的类,有没有办法定义"什么"被比较而不是单独写出来?
class Version:
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
@property
def version(self):
return self.major, self.minor, self.patch
def __eq__(self, other):
return self.version == other.version
def __gt__(self, other):
return self.version > other.version
def __lt__(self, other):
return self.version < other.version
类似的东西,
class Version:
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
def __representation__(self):
return self.major, self.minor, self.patch
...哪个__representation__
会用于所有类似比较的运算符?
答案 0 :(得分:3)
我不知道一次定义所有内容的方法。但是python提供了functools.total_ordering
装饰器,它要求你只编写__eq__
和一个比较魔术方法,然后添加所有其他方法。
示例:
@total_ordering
class Version:
def __init__(self, major, minor, patch):
self.major = major
self.minor = minor
self.patch = patch
@property
def version(self):
return self.major, self.minor, self.patch
def __eq__(self, other):
return self.version == other.version
def __lt__(self, other):
return self.version < other.version