Code: Alles auswählen
$ python2.6
Python 2.6 (r26:66714, Nov 19 2008, 12:48:10)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
... def mygetitem(self, key):
... return 42
... def __init__(self):
... self.__getitem__ = self.mygetitem
...
>>> t = Test()
>>> t['blab']
42
Code: Alles auswählen
$ python3.0
Python 3.0rc1+ (py3k, Oct 28 2008, 09:23:29)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> class Test:
... def __init__(self):
... self.__getitem__ = self.mygetitem
... def mygetitem(self, key):
... return 42
...
>>> t = Test()
>>> t['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Test' object is unsubscriptable
>>>