我试图扩展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
最佳答案
比较运算符do not call
原文链接:https://www.f2er.com/python/439482.html__cmp__
如果the corresponding magic method或其对应项已定义且未返回NotImplemented:
class MyStr(str):
def __gt__(self,return int(self) > int(other)
print MyStr(16) > MyStr(7) # True
P.S.:你可能不希望无害的比较抛出异常:
class MyStr(str):
def __gt__(self,other):
try:
return int(self) > int(other)
except ValueError:
return False