Class 实现自定义最大函数
Class that implements custom max function
我有两个 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
function for the Point class that will return Point(max(self.x, other.x), max(self.y, other.y))
?" The max function seems to just look at the __lt__
和 return 最高。
max()
不能这样做,它只能return作为输入给定的元素之一,不能 产生新实例。
您需要实现自己的功能:
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, ...)
)。
max(a, b)
只能 return a
或 b
- 它不能用新值创建点。
您可以将自己的方法添加到 class 并使用
c = a.max(b)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def max(self, other):
return Point(max(self.x, other.x), max(self.y, other.y))
a = Point(1, 3)
b = Point(4, 2)
c = a.max(b)
print(c.x, c.y)
您可以这样操作,以获得所需的输出:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def max(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(max(self.x, other.x), max(self.y, other.y))
def __repr__(self):
return f'Point{self.x, self.y}'
a = Point(1, 3)
b = Point(4, 2)
a.max(b)
# Point(4, 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
function for the Point class that will return Point(max(self.x, other.x), max(self.y, other.y))
?" The max function seems to just look at the __lt__
和 return 最高。
max()
不能这样做,它只能return作为输入给定的元素之一,不能 产生新实例。
您需要实现自己的功能:
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, ...)
)。
max(a, b)
只能 return a
或 b
- 它不能用新值创建点。
您可以将自己的方法添加到 class 并使用
c = a.max(b)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def max(self, other):
return Point(max(self.x, other.x), max(self.y, other.y))
a = Point(1, 3)
b = Point(4, 2)
c = a.max(b)
print(c.x, c.y)
您可以这样操作,以获得所需的输出:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def max(self, other):
if not isinstance(other, Point):
return NotImplemented
return Point(max(self.x, other.x), max(self.y, other.y))
def __repr__(self):
return f'Point{self.x, self.y}'
a = Point(1, 3)
b = Point(4, 2)
a.max(b)
# Point(4, 3)