|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
小甲鱼python课后题043最后一题的代码实现
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)
这个地方用new的原因是什么?实现了什么样的功能呢?感觉对于new的使用不太了解
本帖最后由 jackz007 于 2021-11-10 09:22 编辑
str 类在创建对象的时候,会直接调用 str . __new__(cls , word) 把 word 照原样直接传给新对象。而新定义的 Word 类继承了 str 类,在创建对象的时候,先对传入对象的字符串 word 进行检查,如果发现其中有空格字符存在,会打印一条信息,然后,把位于字符串第一个空格后面的内容从字符串中去掉,然后,用新的字符串调用 str . __new__(cls , word) 去创建对象。例如,如果定义 Word 对象时,使用了字符串 '123 abc' 来初始化对象,那么,对象的内容将是字符串 '123'。
你可以试一下:
- a = Word('123 abc')
- print(a)
复制代码- >>> 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('123 abc')
- Value contains spaces. Truncating to first space.
- >>> print(a)
- 123
- >>>
复制代码
所以,Word 类存在的价值是可以在新建对象的时候,对传入对象的字符串根据需要进行加工,然后采用被加工过的字符串来创建对象。除此以外,Word 类还重载了 str 类的 >、<、>= 和 <= 四个运算符,当两个对象比大小时,比的是字符串的长度,而原始运算符比较的是字符的 ASCII 编码。
|
|