字符串比较 __Lt__ 运算符 python:

String Comparison __Lt__ operator python:

我希望能够根据属性 - 大小来比较 2 个对象。 以下是正确的吗?因为它不起作用

def __lt__(self, other): 
    if self.size == "small" and other.size == "big":
        return other.size > self.size
    if self.size == "small" and other.size == "medium":
        return other.size > self.size
    if self.size == "medium" and other.size == "big":
        return other.size > self.size

谢谢

问题是您需要 return 布尔值 :

def __lt__(self, other): 
    if self.size == "small" and other.size in ["big", "medium"]:
        return True
    if self.size == "medium" and other.size == "large":
        return True
    if ...

注意。你需要处理所有的可能性