problem with special built-in method __contains__,

E

eboy98

if i have a dictionary name number ....and i want to ask the list
whether a particular key already
exists.
{'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890',
'hexadecimal': '1-9,a-f'}

i got error..after execute

Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
number._contains_("test")
AttributeError: 'dict' object has no attribute '_contains_'
 
P

Paul Hankin

if i have a dictionary name number ....and i want to ask the list
whether a particular key already
exists.


{'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890',
'hexadecimal': '1-9,a-f'}

i got error..after execute

It's __contains__ and not _contains_. But better is just:
'test' in number
 
J

J. Clifford Dyer

if i have a dictionary name number ....and i want to ask the list
whether a particular key already
exists.

{'octal': '1234567', 'binary': '10100101', 'decimal': '1234567890',
'hexadecimal': '1-9,a-f'}

i got error..after execute


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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top