如何重载 Python 的 __bool__ 方法? [复制]

Posted

技术标签:

【中文标题】如何重载 Python 的 __bool__ 方法? [复制]【英文标题】:How to overload Python's __bool__ method? [duplicate] 【发布时间】:2012-02-13 03:51:01 【问题描述】:

可能重复:defining “boolness” of a class in python

我以为这应该打印“False”,为什么它打印“True”?

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

【问题讨论】:

复制overriding bool() for custom class 【参考方案1】:

您应该在 Python 2.x 中定义 __nonzero__()。它仅在 Python 3.x 中重命名为 __bool__()。 (__nonzero__() 这个名字实际上比bool 类型的引入早了很多年。)

【讨论】:

以上是关于如何重载 Python 的 __bool__ 方法? [复制]的主要内容,如果未能解决你的问题,请参考以下文章