Every object is inherently true or false in Python.
Python first tries __bool__ to obtain a direct Boolean value.
If that method is missing, Python tries __len__ to infer a truth value from the object's length.
class Truth: def __bool__(self): return True X = Truth() # from ww w . j a v a2 s .c o m if X: print('yes!') class Truth: def __bool__(self): return False X = Truth() bool(X)
If __bool__ method is missing, Python falls back on length because a nonempty object is considered true:
class Truth: def __len__(self): return 0 X = Truth() # www.j av a 2 s. co m if not X: print('no!')
If both methods are present Python prefers __bool__ over __len__:
class Truth: def __bool__(self): return True # 3.X tries __bool__ first def __len__(self): return 0 # 2.X tries __len__ first # from w w w. j a v a2 s. c o m X = Truth() if X: print('yes!')
If neither truth method is defined, the object is considered true:
class Truth: pass # from w ww.j a va 2 s . c om X = Truth() bool(X)