Overriding 'to boolean' operator in python?
Question:
I’m using a class that is inherited from list as a data structure:
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
All is perfect, but if I use my object of my class inside of an ‘if’, python evaluates it to False if underlying the list has no elements. Since my class is not just list, I really want it to evaluate False only if it’s None, and evaluate to True otherwise:
a = None
if a :
print "this is not called, as expected"
a = CItem()
if a :
print "and this is not called too, since CItem is empty list. How to fix it?"
Answers:
In 2.x: override __nonzero__()
. In 3.x, override __bool__()
.
I’m using a class that is inherited from list as a data structure:
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
All is perfect, but if I use my object of my class inside of an ‘if’, python evaluates it to False if underlying the list has no elements. Since my class is not just list, I really want it to evaluate False only if it’s None, and evaluate to True otherwise:
a = None
if a :
print "this is not called, as expected"
a = CItem()
if a :
print "and this is not called too, since CItem is empty list. How to fix it?"
In 2.x: override __nonzero__()
. In 3.x, override __bool__()
.