在Python中重载'to boolean'运算符?

29 投票
1 回答
7757 浏览
提问于 2025-04-15 11:09

我正在使用一个从列表继承的类作为数据结构:

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 个回答

46

在2.x版本中,你需要重写 __nonzero__() 这个方法。而在3.x版本中,你要重写 __bool__() 这个方法。

撰写回答