|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
原题:
定义一个单词(Word)类继承自字符串,重写比较操作符,当两个 Word 类对象进行比较时,根据单词的长度来进行比较大小。
Fish C的答案:
- 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)
复制代码
我运行不成功:
- ================== RESTART: C:/Users/user/Desktop/20210312a.py =================
- >>> __gt__(apple, cat)
- Traceback (most recent call last):
- File "<pyshell#26>", line 1, in <module>
- __gt__(apple, cat)
- NameError: name '__gt__' is not defined
- >>> Word(apple, cat)
- Traceback (most recent call last):
- File "<pyshell#27>", line 1, in <module>
- Word(apple, cat)
- NameError: name 'apple' is not defined
- >>> __gt__.Word(apple, cat)
- Traceback (most recent call last):
- File "<pyshell#28>", line 1, in <module>
- __gt__.Word(apple, cat)
- NameError: name '__gt__' is not defined
- >>>
复制代码
怎么使用这个程序呀?我晕了。
本帖最后由 jackz007 于 2021-3-16 16:01 编辑
楼主,定义的魔法方法供类实例在使用 >、>= <、<= 进行比较的时候使用,一般不直接调用。
- >>> 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)
- >>> a = Word('ABC')
- >>> b = Word('1234')
- >>> a > b
- False
- >>> a <= b
- True
- >>> a < b
- True
- >>>
复制代码
|
|