__getitem__ method on (meta)classes
Bengt Richter
bokr at oz.net
Tue Mar 15 01:54:22 EST 2005
On Mon, 14 Mar 2005 22:00:38 -0800, Ron Garret <rNOSPAMon at flownet.com> wrote:
>In article <39n1jpF60pc7pU1 at individual.net>,
> Leif K-Brooks <eurleif at ecritters.biz> wrote:
>
>> 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.
>
>Ah.
>
>Did you mean type(x).__getitem__(x,y)?
>
Not if x is a classmethod, since type(x).__getitem__ gets you a bound-to-the-class method
instead of the usual unbound method, which would want the x instance as the first argument.
>>> 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])()
>>> type(f).__getitem__
<bound method type.__getitem__ of <class '__main__.baz'>>
>>> type(f).__getitem__(0)
1
Leaving out the classmethod:
>>> def foo(lst):
... class baz(object):
... def __getitem__(cls, idx): return cls.lst[idx]
... baz.lst = lst
... return baz
...
>>> f = foo([1,2,3])()
>>> type(f).__getitem__
<unbound method baz.__getitem__>
>>> type(f).__getitem__(f, 0)
1
>And where is this documented?
Between the lines in my previous post ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list