Risposte:
È necessario utilizzare il __getitem__metodo di .
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
E se imposterai dei valori, dovrai implementare anche il __setitem__metodo , altrimenti ciò accadrà:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
Per sovraccaricarlo completamente è inoltre necessario implementare i metodi __setitem__e __delitem__.
modificare
Ho quasi dimenticato ... se vuoi emulare completamente un elenco, devi anche __getslice__, __setslice__ and __delslice__.
Ci sono tutti documentati in http://docs.python.org/reference/datamodel.html
Stai cercando il __getitem__metodo. Vedi http://docs.python.org/reference/datamodel.html , sezione 3.4.6
__getslice__,__setslice__` e__delslice__' have been deprecated for the last few releases of ver 2.x (not sure exactly when), and are no longer supported in ver 3.x. Instead, use__getitem__.__setitem__` e__delitem__' and test if the argument is of typefetta, i.e.:se isinstance (arg, slice): ...