我想知道为什么"Word('zhiying')== Word('navaln')"是真的吗?

-6 python class

在python控制台中,我定义了一个名为Word的类.

class Word(str):
    def __new__(cls, word):
        if ' ' in word:
            print("Value contains spaces.Truncating to first space.")
            word = word[:word.index(' ')]
            return str.__new__(cls,word)
    def __gt__(self, other):
        return len(self) > len(other)
    def __lt__(self, other):
        return len(self) < len(other)
    def __ge__(self, other):
        return len(self) >= len(other)
    def __le__(self, other):
        return len(self) <= len(other)
Run Code Online (Sandbox Code Playgroud)

我想知道为什么输出Word('zhiying') == Word('navaln')是真的?

Pau*_*kin 6

因为您的__new__方法返回None任何没有空格的单词.可能你想要取消return声明.您甚至可以在控制台输出中看到此问题 - 当您尝试len(Word('zhiying'))收到错误时NoneType.