__len__ and boolean values - small language change

Michael Hudson mwh21 at cam.ac.uk
Mon May 8 12:57:41 EDT 2000


Andrew Cooke <andrew at andrewcooke.free-online.co.uk> writes:

[snip]
> Is there a special method that I can override to provide boolean values
> in tests, or is __len__ called directly? 

You want __nonzero__:

>>> class L:
...  def __nonzero__(self): return 0
...  def __len__(self): return 1
... 
>>> if L(): print 1
... 

and:

    http://www.python.org/doc/current/ref/sequence-types.html#l2h-16

HTH,
Michael

-- 
  ... but I guess there are some things that are so gross you just have
  to forget,  or it'll destroy something within you.  perl is the first
  such thing I have known.                 -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list