实现自定义最大功能

问题描述 投票:0回答:3

我有两个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类实现自定义max函数?” max函数似乎只是看Point(max(self.x, other.x), max(self.y, other.y))并返回最高值。

python max point
3个回答
3
投票

__lt__ 无法执行此操作,它只能返回作为输入给定的元素之一,not产生新的实例。

您需要实现自己的功能:

__lt__

1
投票

[max()只能返回def max_xy_point(*points): return Point( max(p.x for p in points), max(p.y for p in points) ) max(a, b)-无法使用新值创建点。

您可以将自己的方法添加到类中并使用

a

b

0
投票

您可以这样处理,以获得所需的输出:

c = a.max(b)
© www.soinside.com 2019 - 2024. All rights reserved.