5

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.

darxtrix
  • 2,032
  • 2
  • 23
  • 30

3 Answers3

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

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
1

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

object.__nonzero__ and object.__bool__

Filip Malczak
  • 3,124
  • 24
  • 44