Python 我想知道为什么;Word(';智英';)==Word(';纳瓦尔';)”;这是真的吗?
在python控制台中,我定义了一个名为Word的类Python 我想知道为什么;Word(';智英';)==Word(';纳瓦尔';)”;这是真的吗?,python,class,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)
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)
类词(str):
定义新(cls,word):
如果word中有“”:
打印(“值包含空格。截断到第一个空格。”)
单词=单词[:单词索引(“”)]
返回str.\uuuu new\uuuuu(cls,word)
定义(自身、其他):
返回长度(自身)>长度(其他)
定义(自身、其他):
返回长度(自身)=长度(其他)
定义(自我、其他):
返回len(self),因为您的\uuuuu new\uuuu
方法为任何没有空格的单词返回None
。您可能希望取消对return
语句的登入。您甚至可以在控制台输出中看到这个问题——当您尝试len(Word('zhiying'))
时,您会得到一个关于NoneType
的错误,请尝试查看类型(Word('zhiying'))
是什么…!?我尝试了len(单词('zhiying'),得到了一个错误“TypeError:type'NoneType'的对象没有len()。