|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
动动手最后一题
1. 定义一个单词(Word)类继承自字符串,重写比较操作符(参考自学:Python 魔法方法详解),当两个 Word 类对象进行比较时,根据单词的长度来进行比较大小。
加分要求:实例化时如果传入的是带空格的字符串,则取第一个空格前的单词作为参数。
我的答案
- class Word(str):
- def __init__(self,str1):
- self.str1 = str1.strip()
- if ' ' in self.str1:
- self.str1 = self.str1.split(' ')[0]
- def __lt__(self, other):
- return len(self) < len(other)
- def __le__(self, other):
- return len(self) <=len(other)
- def __eq__(self, other):
- return len(self) == len(other)
- def __ne__(self, other):
- return len(self) != len(other)
- def __gt__(self, other):
- return len(self) > len(other)
- def __ge__(self, other):
- return len(self) >= len(other)
复制代码
因为没有怎么思考, 没有用到__new__, 但是我发现我用 __init__ 好像也没什么太大问题呀 
非要用 __new__吗。。。
有差别的,那些都不是问题,这里主要原因是:
因为 Str 是不可变类型,虽然你在 __init__ 中重新创建了一个 str1
但是对于 Word 类来说,self 实例本身永远是你第一次实例化时候传入的字母
即你可以用你代码试着运行:
- w1 = Word("FishC Python")
- w2 = Word("Lalala")
- print(w1 > w2)
复制代码
你的代码肯定返回 True,而甲鱼哥代码返回的是 False
就是因为甲鱼哥重写了 __new__ 将 self 变为 FishC 而不是 FishC Python
但是你是重写 __init__ ,有因为 str 是不可变的,所以导致你的 self 是传入时的 self,即 FishC Python
你这里创建的 str1 是无用的,在比较运算符中比较的是 self 实例对象的内容,而不是你新定义的 str1 字符串内容
|
|