the 'in' operator and class instances

Gerrit Holl gerrit at nl.linux.org
Sun Jun 8 11:44:51 CEST 2003


Hi,

Vinoo vasudevan wrote:
> >>> 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. :-)

To create this behavious, you would need a metaclass:

  2 >>> class meta(type):
  2 ...  def __contains__(self, o):
  2 ...   return hasattr(self, o)
  2 ...
  3 >>> class Foo:
  3 ...  __metaclass__ = meta
  3 ...  def m(self): pass
  3 ...
  4 >>> 'm' in Foo
True
  5 >>> 'n' in Foo
False

Metaclasses are documented at
http://www.python.org/2.2.3/descrintro.html#metaclasses

This behaviour would hence need to be in "type", not in "object". Foo's
__class__ is "type", so __contains__ is looked up in "type". Python's
builtin types are not open classes, so it would need to be in the language.

yours,
Gerrit.

-- 
138. If a man wishes to separate from his wife who has borne him no
children, he shall give her the amount of her purchase money and the dowry
which she brought from her father's house, and let her go.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list