__getitem__ method on (meta)classes

ron at flownet.com ron at flownet.com
Mon Mar 14 20:43:53 EST 2005


Why doesn't this work?

>>> def foo(lst):
...   class baz(object):
...     def __getitem__(cls, idx): return cls.lst[idx]
...     __getitem__=classmethod(__getitem__)
...   baz.lst = lst
...   return baz
...
>>> f = foo([1,2,3])
>>> f[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsubscriptable object
>>> f.__getitem__(0)
1
>>>


I thought x[y] and x.__getitem__(y) were supposed to always be
synonymous.

Thanks,
rg




More information about the Python-list mailing list