the 'in' operator and class instances

Steven Taschuk staschuk at telusplanet.net
Sun Jun 8 14:18:03 EDT 2003


Quoth Vinoo vasudevan:
  [...]
> >>> class a:
>    def f(self):
>       pass
> 
> >>> 'f' in a
> <Traceback>

Try
    'f' in a.__dict__
(This doesn't check for inherited attributes; for that, use
hasattr.)

> Could somebody tell me why class instances don't use in to check for
> memebership i.e. something like hasattr(..). I read up on "__contains__" in
> the Language Reference. Couldn't python just define a default version of this
> for all classes/instances to check for membership. [...]

It would be a bad idea for instances, since containers want
different semantics.  (They could override __contains__, of
course, but then how would you get the original behaviour?)

For classes, sure, it could be done.  I'm not sure why you'd want
to, though.  Classes are, I admit, containers for their attributes
in a sense, but the additional behaviour which classes have
(inheritance, descriptors, etc.) makes this seem a strained way of
thinking.

  [...]
-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list