我正在尝试扩展一个str并覆盖神奇的方法__cmp__。下面的示例显示了在使用>时,从不调用神奇的方法__cmp__:
class MyStr(str):
def __cmp__(self, other):
print '(was called)',
return int(self).__cmp__(int(other))
print 'Testing that MyStr(16) > MyStr(7)'
print '---------------------------------'
print 'using _cmp__ :', MyStr(16).__cmp__(MyStr(7))
print 'using > :', MyStr(16) > MyStr(7)当运行结果为:
Testing that MyStr(16) > MyStr(7)
---------------------------------
using __cmp__ : (was called) 1
using > : False显然,在使用>时,会调用内置中的底层“比较”功能,在本例中是按字母顺序排序的。
有没有一种方法可以用魔法方法覆盖__cmp__内置函数?如果你不能直接--这里发生了什么,与你可以使用的非魔法方法不同?
发布于 2013-02-28 03:47:50
如果定义了the corresponding magic method或其对应项且不返回NotImplemented,则比较运算符为do not call __cmp__
class MyStr(str):
def __gt__(self, other):
print '(was called)',
return int(self) > int(other)
print MyStr(16) > MyStr(7) # True附言:你可能不希望无害的比较抛出异常:
class MyStr(str):
def __gt__(self, other):
try:
return int(self) > int(other)
except ValueError:
return Falsehttps://stackoverflow.com/questions/15120961
复制相似问题