我有两个Point对象,代码如下所示:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
a = Point(1, 3)
b = Point(4, 2)
max(a, b) # Make this output Point(4, 3)
我的问题是:“如何为将返回
max
的Point类实现自定义 Point(max(self.x, other.x), max(self.y, other.y))
函数?” max函数似乎只是查看 __lt__
并返回最高值。
最佳答案
max()
无法做到这一点,它只能返回作为输入给出的元素之一,而不能产生新的实例。
您需要实现自己的功能:
def max_xy_point(*points):
if not points:
raise ValueError("Need at least 2 points to compare")
if len(points) == 1:
points = points[0]
return Point(
max(p.x for p in points),
max(p.y for p in points)
)
像内置的
max()
函数一样,它可以采用单个序列(max([p1, p2, p3, ...])
或单独的参数(max(p1, p2, p3, ...)
)。
关于python - 实现自定义最大功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895420/