加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 21:53:09 所属栏目: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 '----

我试图扩展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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读