我有两个 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)
Run Code Online (Sandbox Code Playgroud)
我的问题是:“如何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)
)
Run Code Online (Sandbox Code Playgroud)
与内置max()函数一样,这可以采用单个序列(max([p1, p2, p3, ...])或单独的参数 ( max(p1, p2, p3, ...)))。
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |