不确定标题这个问题的最佳方式,但是我如何覆盖或执行min(a, b)我max(a, b)制作的类的对象?我可以像下面一样覆盖gt和 lt 但我想覆盖最小值或最大值,以便我能够使用类似max(a, b, c ,d). 该类也将有多个属性,但我认为对于这个例子来说 2 个就足够了。
class MyClass:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2
def __gt__(self, other):
if isinstance(other, MyClass):
if self.item1 > other.item1:
return True
elif self.item1 <= other.item1:
return False
elif self.item2 > other.item2:
return True
elif self.item2 <= other.item2:
return False
def __lt__(self, other):
if isinstance(other, MyClass):
if self.item1 < other.item1:
return True
elif self.item1 >= other.item1:
return False
elif self.item2 < other.item2:
return True
elif self.item2 >= other.item2:
return False
Run Code Online (Sandbox Code Playgroud)
前任:
a = MyClass(2,3)
b = MyClass(3,3)
print(a > b)
# False
Run Code Online (Sandbox Code Playgroud)
我尝试覆盖,__cmp__但这似乎不起作用。
希望能够执行max(a, b)并返回b对象
小智 5
只需重写比较魔术方法即可。
class A(object):
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __le__(self, other):
return self.value <= other.value
def __eq__(self, other):
return self.value == other.value
def __ne__(self, other):
return self.value != other.value
def __gt__(self, other):
return self.value > other.value
def __ge__(self, other):
return self.value >= other.value
def __str__(self):
return str(self.value)
a = A(10)
b = A(20)
min(a, b)
Run Code Online (Sandbox Code Playgroud)