Can I use a python object in a desired boolean context?
By default any object is True
in boolean context.
>>> class Person():
... pass
...
>>> a=Person()
>>> bool(a)
True
Like bool(0)
returns False
and bool(1)
returns True
.Can i have any way to define an object to have it's boolean value either True
or False
.
Correct me if i'm wrong anywhere,thanks.
class Something(object):
def __nonzero__(self):
return False # Something is False always.
print bool(Something())
Take note __nonzero__
has been renamed to __bool__
in Python 3.x
As pointed out in a comment, you would be better to define __len__
on container like collections. When __len__
returns 0, bool(x)
will evaluate False. Otherwise any positive number above 1 will equate to True.
See the documentation on Truth Value Testing. It first checks if your instance has a __nonzero__
method, if not it uses a __len__
method. The instance is False if __nonzero__
is False or its length is 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With