我试图扩展str和覆盖魔术方法__cmp__.下面的示例显示使用__cmp__时不会调用magic方法>:
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)
Run Code Online (Sandbox Code Playgroud)
运行时导致:
Testing that MyStr(16) > MyStr(7)
---------------------------------
using __cmp__ : (was called) 1
using > : False
Run Code Online (Sandbox Code Playgroud)
显然,当使用>内置的底层"比较"功能时,会调用它,在这种情况下是字母顺序排序.
有没有办法__cmp__用魔术方法覆盖内置?如果你不能直接 - 这里发生的事情与非魔术方法有什么不同?
如果定义了相应的魔术方法或其对应方法并且不返回,则比较运算符不会调用__cmp__:NotImplemented
class MyStr(str):
def __gt__(self, other):
print '(was called)',
return int(self) > int(other)
print MyStr(16) > MyStr(7) # True
Run Code Online (Sandbox Code Playgroud)
PS:您可能不希望无害的比较引发异常:
class MyStr(str):
def __gt__(self, other):
try:
return int(self) > int(other)
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |