30

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?" 
1
  • 1
    +1 since you appear to uncover yourself another wonderful Python gem :) Commented Aug 14, 2009 at 21:35

1 Answer 1

47

In 2.x: override __nonzero__(). In 3.x, override __bool__().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.