【问题标题】:Class that implements custom max function实现自定义 max 函数的类
【发布时间】:2020-05-10 17:17:30
【问题描述】:

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

我的问题是:“如何为将返回 Point(max(self.x, other.x), max(self.y, other.y)) 的 Point 类实现自定义 max 函数?” max 函数似乎只看__lt__ 并返回最高值。

【问题讨论】:

  • def max(self, other): return Point(max(self.x, other.x), max(self.y, other.y)) ?
  • max(a, b) 可以返回 a 或 b - 它不能生成具有不同值的新点。
  • @furas 好吧,那太糟糕了。所以这是 Python 的限制?
  • @furas:至少是内置的max。一个人可以写一个新的max,就像你在第一条评论中建议的那样,但不绑定到Point 类。不过我不会推荐这个
  • 每次只限两点吗?还是2或更多分?

标签: python max point


【解决方案1】:

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, ...))。

【讨论】:

    【解决方案2】:

    max(a, b) 只能返回 a 或 b - 它不能使用新值创建点。

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

    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)
    

    【讨论】:

      【解决方案3】:

      你可以这样做,以获得所需的输出:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多