定义一个单词(Word)类继承自字符串,重写比较操作符
当两个 Word 类对象进行比较时,根据单词的长度来进行比较大小(原来是根据ASCII码比较的)
实例化时如果传入的是带空格的字符串,则取第一个空格前的单词作为参数。
class Word(str):
def __init__(self, a): # 在这重写父类的方法,对输入的字符串预处理(检查是否有空格)
if ' ' in a: # a为待输入的参数
(self.b, self.c) = a.split(' ', 1)
self.d = self.b # 有空格,则把第一个单词赋给d
else:
self.d = a # 无空格,则原单词赋值给d
def __lt__(self, other): # <
return len(self.d) < len(other) #用d比较(这里的self.d可以理解为:实例名.d)
def __le__(self, other): # <=
return len(self.d) <= len(other)
def __eq__(self, other): # ==
return len(self.d) == len(other)
def __ne__(self, other): # !=
return len(self.d) != len(other)
def __gt__(self, other): # >
return len(self.d) > len(other)
def __ge__(self, other): # >=
return len(self.d) >= len(other)
运行:
li1 = Word('iii lll')
li2 = Word('JJJJ')
print(li1 <= li2 )
print(li1.d)
print(li2.d)
结果:
True
iii
JJJJ