覆盖自定义类的 bool() [英] overriding bool() for custom class

查看:23
本文介绍了覆盖自定义类的 bool()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的只是让 bool(myInstance) 返回 False(并且让 myInstance 在 if/or/and 这样的条件下评估为 False.我知道如何覆盖 >, <, =)

All I want is for bool(myInstance) to return False (and for myInstance to evaluate to False when in a conditional like if/or/and. I know how to override >, <, =)

我已经试过了:

class test:
    def __bool__(self):
        return False

myInst = test()
print bool(myInst) #prints "True"
print myInst.__bool__() #prints "False"

有什么建议吗?

(我使用的是 Python 2.6)

(I am using Python 2.6)

推荐答案

这是 Python 2.x 还是 Python 3.x?对于 Python 2.x,您希望改写 __nonzero__.

Is this Python 2.x or Python 3.x? For Python 2.x you are looking to override __nonzero__ instead.

class test:
    def __nonzero__(self):
        return False

这篇关于覆盖自定义类的 bool()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆