What method does slice notation call?

Peter Otten __peter__ at web.de
Thu Oct 9 03:43:53 EDT 2003


Robert Brewer wrote:

>>>> class A(types.DictType):
> ...   def __getitem__(self, key):
> ...           return types.DictType.__getitem__(self, key)
> ...
>>>> a = A()
>>>> a[0] = 3
>>>> a.__getitem__ = lambda x: "w00t"
>>>> a.__getitem__(0)
> 'w00t'
>>>> a
> {0: 3}
>>>> a[0]
> 3
> 
> Can anyone tell me why a[0] doesn't return "w00t", like I thought it
> would? What method is a[0] calling? Is there a way to override it?

The special methods are somewhat reluctant when you try to override them on
the instance level. Here are two ways using brute force.
(There are probably more elegant ways that involve metaclasses...)

Peter

<code>
import types

# implement __getitem__() in terms of a "normal" method
# that can be overridden on a per instance basis
class A(types.DictType):
    def getitem(self, key):
        return types.DictType.__getitem__(self, key)
    def __getitem__(self, key):
        return self.getitem(key)

a = A()
a.getitem = lambda key: "if you must"

print a["dummy"]

# just subclassing...
class B(A):
    __getitem__ = lambda self, key: "there you are"

b = B()
print b["dummy"]
</code>




More information about the Python-list mailing list