python - 实现自定义最大功能

标签 python max point

我有两个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/

相关文章:

python - 如果我必须删除子数组中的最大元素,如何找到子数组的最大和

python - 组合两个numpy数组以形成一个数组,每个数组中的最大值

android 2点之间有多少像素

javascript - 使用 D3.js 绘制 map 上的点

python - Matplotlib,损坏的图形表示错误

Python 最大值和最小值

python - Python 中的 YouTube 下载链接生成器

Javascript: rect.contains(点)

python - .gitignore 符号中的 "py[cod]"和 "pyc"有什么区别?

python - 查找 pyLightGBM 的 LightGBM 路径