How to overload Python's __bool__ method?
24,532
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.)
Author by
dividebyzero
I am a enthusiast in science and philosophy in general. I am a chemist by training. But is currently doing computer programming for work. I am especially interested in the following: Biology: Evolutionary biology, Genomics, Neural Science Computers: Operation systems Programming languages Distributed computing
Updated on September 02, 2020Comments
-
dividebyzero almost 4 years
Possible Duplicate:
defining “boolness” of a class in pythonI 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 >>>
-
Mehmet Kaan ERKOÇ about 2 yearsIt is strange that I could not find that information anywhere else but in your answer. Thanks a lot !
-
Sven Marnach about 2 years@MehmetKaanERKOÇ The documentation for most of the magic methods is on the data model page of the Python reference. Differences between Python 2 and 3 are mostly documented in the What's New page of Python 3.0. I'll admit this is not easy to find if you don't know what you are looking for.