the 'in' operator and class instances

John Roth johnroth at ameritech.net
Sun Jun 8 13:43:01 EDT 2003


"Vinoo vasudevan" <ee01b092 at ee.iitm.ernet.in> wrote in message
news:mailman.1055063152.22684.python-list at python.org...
> Hi,
> I'm an newbie and have been getting to know Python over the past two
weeks.
> One of the things I really liked was the 'in' operator. Statements
like "key
> in dict" or "line in file" are really cool. But this doesn't seem to
work for
> classes. i.e.
>
> >>> class a:
>    def f(self):
>       pass
>
> >>> 'f' in a
> <Traceback>
>
> 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. Any class that
attaches a
> special meaning to membership can of course define its own
"__contains__". In
> c++ terminology (my __previous__ language :-) ) : can't "object"
define a
> virtual function "__contains__"? Just a suggestion. Plz let me know if
I don't
> have a clue of I'm talking about. :-)

The standard method of implementing the "in" operator depends on the
class implementing enough of the sequence protocol so that the
interpreter can iterate through it to find (or not find) the requested
item. See topic 3.3 in the Python Reference Manual (2.2.2 version.)

It can also implement the __contains__() method if it doesn't want to
look like a sequence.

John Roth

>
>
> Vinoo
>
>






More information about the Python-list mailing list