我正在尝试扩展 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__
内置函数?如果您不能直接使用 - 这里发生的事情与您可以使用的非魔法方法有何不同?
最佳答案
比较运算符 do not call __cmp__
如果the corresponding magic method或其对应物已定义且不返回 NotImplemented
:
class MyStr(str):
def __gt__(self, other):
print '(was called)',
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
关于python - 在扩展 python 中的内置函数时,你可以覆盖魔术方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15120961/