|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class Word(str):
'''存储单词的类,定义比较单词的几种方法'''
def __new__(cls, word):
# 注意我们必须要用到 __new__ 方法,因为 str 是不可变类型
# 所以我们必须在创建的时候将它初始化
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)
弱弱的问一句,为什么要重写 __gt__,__lt__, __ge__, __le__ 这些魔法方法呢?
本帖最后由 jackz007 于 2020-11-19 10:54 编辑
Word 类继承自 str,如果不写这些魔法方法,当对象之间使用 > 、< 、>=、<= 进行比较的时候,就会缺省使用 str 类的魔法方法,这些魔法方法只考虑了字符串的字符编码,忽略了字符串的长度,而我们需要的是,只考虑字符串长度,无视字符串编码的比较结果,所以,就需要重写这些魔法方法。
看看下面的例子就明白了
- >>> 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)
- >>> a = Word('abc')
- >>> b = Word('b')
- >>> a > b
- True
- >>> a = 'abc'
- >>> b = 'b'
- >>> a > b
- False
- >>>
复制代码
|
|