__getitem__ and arguments

Andy Jewell andy at wild-flower.co.uk
Sat Jul 19 09:16:42 EDT 2003


On Saturday 19 Jul 2003 10:10 am, KanZen wrote:
> I'm trying to understand the difference between __setitem__ and an
>
> ordinary method. For example:
> >>> 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
>
> For __getitem__() the arguments become a tuple. I can't seem to find
> this in the language spec. Can anybody explain this to me?
>
> Thanks,
> KanZen.


Maybe the following will help:

-------------8<----------
>>> class A(object):
	def __getitem__(self,*args):
		print args
	def test(self,*args):
		print args

		
>>> a=A()
>>> a[1]
(1,)
>>> a[1:2]
(slice(1, 2, None),)
>>> a.__getitem__(1)
(1,)
>>> a.test(1)
(1,)
-------------8<----------

This tells us what we could already guess from the formal parameter list: 
*args returns a tuple of the arguments.  

Try:

-------------8<----------
>>> class A(object):
	def __getitem__(self,index):
		print index
	def test(self,index):
		print index

		
>>> a=A()
>>> a[1]
1
>>> a[1:2]
slice(1, 2, None)
>>> a.__getitem__(1)
1
>>> a.test(1)
1
-------------8<----------

As you can see, both methods do the same.  I think you're just seening the 
effect of the variable arguments syntax.  

I'm sure a Guru will correct me if I'm wrong, but I don't see evidence of a 
'special case' here... ;-)

hth
-andyj





More information about the Python-list mailing list