如何选择将为内置min()和max()函数计算的用户定义类的属性?

sga*_*a62 0 python class object max min

我想在我的对象集合上使用Python的内置min()max()函数Point.但是,我希望该distance属性是比较值.如何在类定义中指定它?

class Point():
    def __init__(self, x, y, distance):
        self.x = x
        self.y = y
        self.distance = distance

a = Point(3, 5, 2)
b = Point(5, 4, 1)
c = Point(8, 4, 5)

hopefully_b = min(a, b, c)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

您可以使用键功能:

from operator import attrgetter

max(a, b, c, key=attrgetter('distance'))
Run Code Online (Sandbox Code Playgroud)

operator.attrgetter()函数生成一个callable,它返回传递给它的每个对象的命名属性.你可以通过lambdacallable 实现同样的目标:

max(a, b, c, key=lambda p: p.distance)
Run Code Online (Sandbox Code Playgroud)

或者,您可以向类添加特殊方法以定义它们的比较方式; 该__eq__方法定义了两个实例是如何相等的,并且__lt__在比较两个实例以查看它们如何排序时使用了类似于和朋友的方法.max()然后将使用这些方法找到一个没有key函数的"最大"项.

有了@functools.total_ordering()装饰器,你只需要实现其中两个; __eq__和比较方法之一:

from functools import total_ordering

@total_ordering
class Point():
    def __init__(self, x, y, distance):
        self.x = x
        self.y = y
        self.distance = distance

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented  # only the same type or subclasses
        return (self.x, self.y, self.distance) == (other.x, other.y, other.distance)

    def __lt__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented  # only the same type or subclasses
        if (self.x, self.y) == (other.x, other.y):
            return False  # same coordinates makes them equalish?
        return self.distance < other.distance
Run Code Online (Sandbox Code Playgroud)

对于Point物体,这应该更多考虑; 例如,如果距离不相等但x和y是什么会发生什么?