problem with special built-in method __contains__,

J. Clifford Dyer jcd at sdf.lonestar.org
Tue Oct 2 14:49:01 CEST 2007


On Tue, Oct 02, 2007 at 11:14:38AM -0000, eboy98 at gmail.com wrote regarding problem with special built-in method   __contains__,:
> 
> if i have a dictionary  name number ....and i want to    ask the list
> whether a particular key already
> exists.
> 
> >>> print number
> {'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890',
> 'hexadecimal': '1-9,a-f'}
> 
>  i got  error..after execute
> 
>  >>>number._contains_("test")
> 
> Traceback (most recent call last):
>   File "<pyshell#15>", line 1, in <module>
>     number._contains_("test")
> AttributeError: 'dict' object has no attribute '_contains_'
> 

First of all, the special methods contain a *double* underscore before and after the name, so it's not _contains_, it's __contains__.

Secondly, for most basic operations, you shouldn't have to use these special methods directly.  They are bound to other funtionality in Python.  So instead of:


number.__contains('test')

try the following:

'test' in number  

Cheers,
Cliff



More information about the Python-list mailing list