How to overload Python's __bool__ method?

PythonMethodsOverloadingMagic Methods

Python Problem Overview


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

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 Solutions


Solution 1 - Python

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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondividebyzeroView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow