On Mon, 14 Mar 2005 22:00:38 -0800, Ron Garret <[EMAIL PROTECTED]> wrote:
>In article <[EMAIL PROTECTED]>, > Leif K-Brooks <[EMAIL PROTECTED]> wrote: > >> [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list