__getitem__ method on (meta)classes
Leif K-Brooks
eurleif at ecritters.biz
Mon Mar 14 22:05:12 EST 2005
ron at flownet.com wrote:
> 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
> ...
>
> I thought x[y] and x.__getitem__(y) were supposed to always be
> synonymous.
No, with new-style classes, x[y] and type(x).__getitem__(y) are
synonymous. This works:
>>> def foo(lst):
... class bar(type):
... def __getitem__(self, index):
... return self.lst[index]
... class baz(object):
... __metaclass__ = bar
... baz.lst = lst
... return baz
...
>>> foo([1,2,3])[0]
1
More information about the Python-list
mailing list