覆盖自定义类布尔() [英] overriding bool() for custom class
本文介绍了覆盖自定义类布尔()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要的是布尔(将myInstance)返回false(以及将myInstance评估为False时,在条件一样,如果/或/和。我知道如何重写>,&LT,=)
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的您正在寻找重写 __ __非零
代替。
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
这篇关于覆盖自定义类布尔()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文