What method does slice notation call?
Robert Brewer
fumanchu at amor.org
Thu Oct 9 14:33:56 EDT 2003
Alex Martelli wrote:
> For all except "classic classes" (which have to do lots of hacking
> behind the scenes for backwards compatibility, sigh), a[0] means
> roughly the equivalent of:
>
> getattr(type(a), '__getitem__')(a, 0)
>
> so, if you want to have a[0] invoke something different, you must
> change type(a) accordingly, e.g.:
>
> def changeindexing(a, newgetitem):
> class x(type(a)):
> __getitem__ = newgetitem
> a.__class__ = x
Peter Otten wrote:
> The special methods are somewhat reluctant when you try to
> override them on the instance level.
> ...
> class A(types.DictType):
> def getitem(self, key):
> return types.DictType.__getitem__(self, key)
> def __getitem__(self, key):
> return self.getitem(key)
Thanks to you both! I'm a bit rushed on this current project; I'll
probably investigate the class rebinding next month. Since the sequence
in question is itself an instance attribute, I decided to just use
custom getter and setter methods (somewhat the inverse of Peter's
solution; I'm wrapping the item call in another function, instead of
wrapping another function in the item call):
class A(types.DictType):
_data = {}
def getitem(self, key):
return self._data[key]
In this way, I can both override getitem() in subclasses of A, and
rebind getitem() if I need to. Vielen dank!
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list