【问题标题】:Overriding <= and >= for Python Class为 Python 类覆盖 <= 和 >=
【发布时间】:2020-04-14 11:45:58
【问题描述】:

我有以下课程:

class Word:
    def __init__(self, key: str):
        self.key = key
        self.value = ''.join(sorted(key))

    def __lt__(self, other):
        if self.value < other.value:
            return True
        return False

    def __gt__(self, other):
        if self.value > other.value:
            return True
        return False

    def __eq__(self, other):
        val = other.value
        if self.value == val:
            return True
        return False

TypeError: '<=' not supported between instances of 'Word' and 'Word'

如何为 python 类覆盖

【问题讨论】:

标签: python


【解决方案1】:

你需要实现__ge__ & __le__

class Word:
    def __init__(self, key: str):
        self.key = key
        self.value = ''.join(sorted(key))

    def __lt__(self, other):
        if self.value < other.value:
            return True
        return False

    def __gt__(self, other):
        if self.value > other.value:
            return True
        return False

    def __le__(self, other):
        if self.value <= other.value:
            return True
        return False

    def __ge__(self, other):
        if self.value >= other.value:
            return True
        return False

    def __eq__(self, other):
        val = other.value
        if self.value == val:
            return True
        return False

【讨论】:

    【解决方案2】:

    您还需要覆盖def __le__(self, other)(小于等于)和def __ge__(self, other)(大于等于)。

    除此之外,您应该检查给定的other 是否真的是Word 实例,否则您可能会因为无法访问other.value 而崩溃:

    w = Word("hello")
    print( w > 1234 )  # crash:  AttributeError: 'int' object has no attribute 'value'
    

    所有这些的来源/文档:object.__le__


    比较的潜在修复:

    def __lt__(self, other):
        if isinstance(other, Word):
            if self.value < other.value:
                return True
        else:
            # return True or False if it makes sense - else use better exception
            raise ValueError(f"Cannot compare Word vs. {type(other)}")
        return False
    

    【讨论】:

      【解决方案3】:

      还有另外一种特殊的方法:

       def __le__(self, other):
          if self.value <= other.value:
              return True
          else:
              return False
      

      【讨论】:

        猜你喜欢
        • 2011-04-28
        • 2020-06-16
        • 1970-01-01
        • 2017-05-11
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        • 2022-11-03
        • 1970-01-01
        相关资源
        最近更新 更多