Overloading __getitem__

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat May 24 15:54:08 EDT 2008


En Thu, 22 May 2008 20:38:39 -0300, Andreas Matthias <amat at kabsi.at> escribió:

> inhahe at gmail.com wrote:
>
>> actually i ddin't think about the fact that you're overloading dict, which
>> can already take multiple values in getitem
>
> Oh, I didn't know that. I totally misinterpreted the error message.
>
>
>> so how about
>>
>> class crazy: pass
>>
>> and then in your dict class:
>>
>> def __getitem__(*args):
>
> Apparently, args already is a tuple, so this should be:
>
>   def __getitem__(self, args):
>
> Is this documented somewhere? I couldn't find it anywhere.

No, that's not correct. First, there is nothing special with the arguments to dict.__getitem__ -- except that the syntax obj[index] provides a delimiter and it allows for obj[a,b] as a shortcut for obj[(a,b)] -> obj.__getitem__((a,b))

You may use the *args notation in any function; it is always a tuple (a singleton, when you call the function with only one argument)

py> def foo(*args): print args
...
py> foo(1)
(1,)
py> foo(1,2)
(1, 2)
py> foo((1,2))
((1, 2),)

Compare with:

py> def bar(arg): print arg
...
py> bar(1)
1
py> bar(1,2)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: bar() takes exactly 1 argument (2 given)
py> bar((1,2))
(1, 2)

-- 
Gabriel Genellina




More information about the Python-list mailing list