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

gri*_*yvp 23 python

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

class CItem( list ) :
  pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
Run Code Online (Sandbox Code Playgroud)

一切都很完美,但是如果我在'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?"
Run Code Online (Sandbox Code Playgroud)

Joh*_*kin 38

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