在Python中重载'to boolean'运算符?
我正在使用一个从列表继承的类作为数据结构:
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
一切都很好,但如果我在一个'if'语句中使用我的类的对象,Python会判断它为False,前提是这个列表里面没有元素。因为我的类不仅仅是一个列表,我希望它只有在为None的时候才判断为False,其他情况下都判断为True:
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?"