首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中扩展内建时,你能重写一个魔术方法吗?

在python中扩展内建时,你能重写一个魔术方法吗?
EN

Stack Overflow用户
提问于 2013-02-28 03:45:20
回答 1查看 196关注 0票数 5

我正在尝试扩展一个str并覆盖神奇的方法__cmp__。下面的示例显示了在使用>时,从不调用神奇的方法__cmp__

代码语言:javascript
复制
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)

当运行结果为:

代码语言:javascript
复制
Testing that MyStr(16) > MyStr(7)
---------------------------------
using __cmp__ : (was called) 1
using > : False

显然,在使用>时,会调用内置中的底层“比较”功能,在本例中是按字母顺序排序的。

有没有一种方法可以用魔法方法覆盖__cmp__内置函数?如果你不能直接--这里发生了什么,与你可以使用的非魔法方法不同?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-28 03:47:50

如果定义了the corresponding magic method或其对应项且不返回NotImplemented,则比较运算符为do not call __cmp__

代码语言:javascript
复制
class MyStr(str):
    def __gt__(self, other):
        print '(was called)',
        return int(self) > int(other)


print MyStr(16) > MyStr(7)   # True

附言:你可能不希望无害的比较抛出异常:

代码语言:javascript
复制
class MyStr(str):
    def __gt__(self, other):
        try:
            return int(self) > int(other)
        except ValueError:
            return False
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15120961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档