在python中扩展内置时,你能覆盖一个神奇的方法吗?

Roc*_*man 5 python

我试图扩展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__用魔术方法覆盖内置?如果你不能直接 - 这里发生的事情与非魔术方法有什么不同?

Pav*_*sov 4

如果定义了相应的魔术方法或其对应方法并且不返回,则比较运算符不会调用__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)

  • 通过重写 [`__lt__()` 和 `__gt__()` `str` 的方法可以强制 `>` 运算符调用 `__cmp__()` 以返回 `NotImplemented`](http://ideone.com/rC5D8v )即,您的答案中的“如果定义了任何其他魔法比较方法”是不精确的。为了保持一致性,应定义所有方法或不定义任何方法:`__lt__()`、`__gt__()`、`__le__()`、`__ge__()`、`__eq__()`、`__ne__()`、还有`__hash__()`。 (2认同)