|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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)
复制代码
这段代码最后的
def __gt__(self, other)
def __lt__(self, other)
def __ge__(self, other)
def __le__(self, other)
这几个是重写的意思吗?运行后到底是怎么比较两个字符串的。。。
def __gt__(self, other)
def __lt__(self, other)
def __ge__(self, other)
def __le__(self, other)
这几个是重写的意思吗?运行后到底是怎么比较两个字符串的。。。
你类写上了这些魔法方法后就算是重写了,self 是指类的实例 other 是 另一个变量
|
|