The key point here is the realization that self[k] same as self.__getitem__(k) , so you don't want to use self[k] inside __getitem__ unless you are actually trying to do some recursion. Instead, always use OrderedDict.__getitem__ (self,key) .
In an unrelated note, you generally donβt want to create a method that simply calls the same method of the parent class, that is:
class MyArray (OrderedDict): def __init__ (self,*args): OrderedDict.__init__(self,*args)
Just delete this method and python will call the parent class method for you, the inheritance will be awesome :).
update:
After some digging, I found that you get infinite recursion when trying to print MyArray , because OrderedDict.__repr__ calls OrderDict.items , which then calls OrderDict.__getitem__ (in the form of self[key] ), then it calls __repr__ for each of the elements. .. The problem is that you are __getitem__ to do something very different from what it does in the parent class. If you want this class to have the full functionality of the python class, you need to override each method that uses self[key] anywhere in the method. You can start with items , i.e. something like:
def items(self): 'od.items() -> list of (key, value) pairs in od' return [(key, OrderedDict.__getitem__(self, key)) for key in self]
When you come across similar things, it is often better to discard the subclass and just have OrderedDict as an attribute of the new class, for example:
class MyArray(object): def __init__(self, *args): self.data = OrderedDict(*args) def __getitem__(self, key): if not hasattr (key, '__iter__'): return MyArray([(key, self.data[key])]) return MyArray([(k, self.data[k]) for k in key])