git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Understanding the MRO with multiple inheritance


I basically had defined 4 classes. SimpleList be the base class for all the other 3 classes. SortedList and IntList both being the child of the base class SimpleList. They have a single inheritance relationship. Now I have the last class called SortedIntList which has multiple inheritance relationship with IntList and SortedList. The classes looks like:

class SimpleList:
    def __init__(self, items):
        self._items = list(items)

    def add(self, item):
        self._items.append(item)

    def __getitem__(self, index):
        return self._items[index]

    def sort(self):
        self._items.sort()

    def __len__(self):
        return len(self._items)

    def __repr__(self):
        return "SimpleList({!r})".format(self._items)

class SortedList(SimpleList):
    def __init__(self, items=()):
        super().__init__(items)

    def add(self, item):
        super().add(item)
        self.sort()

    def __repr__(self):
        return "SortedList({!r})".format(list(self))


class IntList(SimpleList):
    def __init__(self, items=()):
        for x in items:
            self._validate(x)
        super().__init__(items)

    @staticmethod
    def _validate(x):
        if not isinstance(x, int):
            raise TypeError('IntList only supports integer values.')

    def add(self, item):
        self._validate(item)
        super().add(item)

    def __repr__(self):
        return "IntList({!r})".format(list(self))


class SortedIntList(IntList, SortedList):
    def __repr__(self):
        return "SortedIntList({!r})".format(list(self))


Now when I call the add method on the SortedIntList class?s instance, I was expecting super.add() call inside the IntList class add method will dispatch it to the base class SimpleList. But in reality it doesn?t, it rather forwards it to the SortedList add method. How MRO guides here can anyone explain please?

I am little lost in the chain.

ob = SortedIntList((2,4,3))
ob.add(0)
print(ob)
# SortedIntList([0, 2, 3, 4])


Thanks,

Arup Rakshit
ar at zeit.io