What is the name of the method to override the [] operator (subscript notation) for a class in Python?
            Asked
            
        
        
            Active
            
        
            Viewed 1.8e+01k times
        
    335
            
            
        3 Answers
436
            You need to use the __getitem__ method.
class MyClass:
    def __getitem__(self, key):
        return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
 
    
    
        nairboon
        
- 678
- 5
- 15
 
    
    
        David Webb
        
- 190,537
- 57
- 313
- 299
86
            
            
        To fully overload it you also need to implement the __setitem__and __delitem__ methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__.
There are all documented in http://docs.python.org/reference/datamodel.html
 
    
    
        Dave Kirby
        
- 25,806
- 5
- 67
- 84
- 
                    92`__getslice__, `__setslice__` and `__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__` and `__delitem__' and test if the argument is of type `slice`, i.e.: `if isinstance(arg, slice): ... – Don O'Donnell Dec 25 '09 at 18:15
23
            
            
        You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6
 
    
    
        Confusion
        
- 16,256
- 8
- 46
- 71
 
    