Assigning (instead of defining) a __getitem__ magic method breaks indexing [duplicate]

Special methods (essentially anything with two underscores on each end) have to be defined on the class. The internal lookup procedure for special methods completely skips the instance dict. Among other things, this is so if you do

class Foo(object):
    def __repr__(self):
        return 'Foo()'

the __repr__ method you defined is only used for instances of Foo, and not for repr(Foo).

Leave a Comment