class Foo(str):
def __new__(cls, word):
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)
这里重载了多个比较符,是核心是按照字符串的长度进行比较,越长的越大。这里看似返回的是一个表达式,但是函数在真正返回的时候会将这个表达式计算出来,也就是说最终返回的其实还是布尔值。
class Foo(str):
def __new__(cls, word):
return str.__new__(cls, word)
def __eq__(self, other):
if ('scolia' in self ) and ('scolia' in other):
return True
else:
return False
b = Foo('scolia')
a = 'scolia123'
print a == b
print b == a
class Foo(str):
def __new__(cls, word):
return str.__new__(cls, word)
def __eq__(self, other):
if ('scolia' in self ) and ('scolia' in other):
return True
else:
return False
class Boo(str):
def __new__(cls, word):
return str.__new__(cls, word)
def __eq__(self, other):
if ('scolia' in self ) and ('scolia' in other):
return False
else:
return True
a = Foo('scolia')
b = Boo('scolia')
print a == b
print b == a