在python中覆盖'to boolean'运算符?

时间:2009-04-17 18:15:28

标签: python

我正在使用从list继承的类作为数据结构:

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?"

1 个答案:

答案 0 :(得分:37)

在2.x中:覆盖__nonzero__()。在3.x中,覆盖__bool__()