__getitem__ and arguments

Ben Finney bignose-hates-spam at and-zip-does-too.com.au
Sat Jul 19 14:10:05 EDT 2003


On 19 Jul 2003 02:10:25 -0700, KanZen wrote:
> I'm trying to understand the difference between __setitem__ and an
> ordinary method. For example:

(presuming you mean __getitem__)

>>>> class A(object):
>       def __getitem__(self, *args):
>         print len(args)
>       def normalMethod(self, *args):
>         print len(args)
> 
>>>> a=A()
>>>> a.normalMethod(1, 2, 3)
> 3
>>>> a[1, 2, 3]
> 1

The dictionary access syntax you used specifies a key, which forces
everything between [] to become a single argument.  In this case, it's a
tuple, (1, 2, 3).

Thus, the args for A.__getitem__() is a tuple of length one, containing
the specified key: the tuple (1, 2, 3).  That is, args is a tuple
containing a tuple.

No such coercion occurs for function syntax; the difference is that you
didn't invoke __getitem__ with function syntax.

>>> class A:
...     def normal_method( self, *args ):
...             print len( args )
...             print type( args )
...             print args
...     def __getitem__( self, *args ):
...             print len( args )
...             print type( args )
...             print args
...
>>> a = A()
>>> a.normal_method( 1, 2, 3 )
3
<type 'tuple'>
(1, 2, 3)
>>> a[ 1, 2, 3 ]
1
<type 'tuple'>
((1, 2, 3),)
>>>

> For __getitem__() the arguments become a tuple.

Yes, because you've specified a key, which by definition is a single
argument.

-- 
 \     "He may look like an idiot and talk like an idiot but don't let |
  `\           that fool you. He really is an idiot."  -- Groucho Marx |
_o__)                                                                  |
http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B




More information about the Python-list mailing list