如何重载Python的__bool__方法? [英] How to overload Python's __bool__ method?

查看:75
本文介绍了如何重载Python的__bool__方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
定义"boolness" python中的类

Possible Duplicate:
defining “boolness” of a class in python

我认为这应该打印"False",为什么要打印"True"?

I thought this should print "False", why is it printing "True"?

>>> class Foo(object):
...   def __bool__(self):
...     return False
... 
>>> f = Foo()
>>> if f:
...   print "True"
... else:
...   print "False"
... 
True
>>>

推荐答案

您应在Python 2.x中定义__nonzero__().在Python 3.x中仅将其重命名为__bool__(). (名称__nonzero__()实际上比bool类型的引入要早很多年.)

You should define __nonzero__() in Python 2.x. It was only renamed to __bool__() in Python 3.x. (The name __nonzero__() actually predates the introduction of the bool type by many years.)

这篇关于如何重载Python的__bool__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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