python - 在扩展 python 中的内置函数时,你可以覆盖魔术方法吗?

标签 python

我正在尝试扩展 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/

相关文章:

Python Jupyter Notebook 无法打开文件,可能输出太大

python - 为什么 Python 对可以嵌套的静态 block 的数量有限制?

python - Django - 如何使用带有 'if' 和 'else' 检查的自定义模板标签?

Python mysql建表错误

Python 二进制 EOF

python - 如何使用 Python 2.7 发送 HTTP POST

python - 如何将 Python 的 subprocess.call() 输出重定向到文件?

python - 使用 python 和 matplotlib 同时获取数据和更新图形

file - 如何以 python 方式从行号边界内的文本文件中获取文本?

python - 如何删除整数列表中的最后一个逗号?