【问题标题】:python - native approach to comparing objectspython - 比较对象的本机方法
【发布时间】:2018-04-11 11:14:57
【问题描述】:

我有一个简单的 python 类,我希望能够进行比较。所以我实现了比较运算符。然后我意识到我一直在为这么多类做同样的事情,感觉很像代码重复。

class Foo(object):
    def __init__(self, index, data):
        self.index = index
        self.data = data

    def __lt__(self, other):
        return self.index < other.index

    def __gt__(self, other):
        return self.index > other.index

    def __le__(self, other):
        return self.index <= other.index

    def __ge__(self, other):
        return self.index >= other.index

    def __eq__(self, other):
        return self.index == other.index

    def __ne__(self, other):
        return self.index != other.index

所以我认为一个简单的解决方案是这样的:

class Comparable(object):
    def _compare(self, other):
        raise UnimplementedError()

    def __lt__(self, other):
        return self._compare(other) < 0

    def __gt__(self, other):
        return self._compare(other) > 0

    def __le__(self, other):
        return self._compare(other) <= 0

    def __ge__(self, other):
        return self._compare(other) >= 0

    def __eq__(self, other):
        return self._compare(other) == 0

    def __ne__(self, other):
        return self._compare(other) != 0

class Foo1(Comparable):
    def _compare(self, other):
        return self.index - other.index

class Foo2(Comparable):
    def _compare(self, other):
        # ...

class Foo3(Comparable):
    def _compare(self, other):
        # ...

但它看起来很基础,我觉得我在这里重新发明了轮子。

我想知道是否有更“原生”的方式来实现这一点。

【问题讨论】:

标签: python


【解决方案1】:

in the docs 所述,您可以使用functools.total_ordering 在编写所有比较时保存一些样板

为了避免提供所有六个函数的麻烦,您可以实现__eq____ne__,并且只实现一个排序运算符,并使用functools.total_ordering() 装饰器来填充其余部分。

明确地说,它们所指的六个函数是:__eq____ne____lt____le____gt____ge__

【讨论】:

    【解决方案2】:

    因此,您希望在创建丰富的比较方法时实现一些自动化。您可以使用functools.total_ordering() 高阶函数来实现此行为。有关详细信息,请参阅reference

    【讨论】:

      猜你喜欢
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 2012-02-13
      相关资源
      最近更新 更多