newprogrammer
newprogrammer

Reputation: 15

Python: new class, inheriting and overriding

I am trying to create a new class in Python, MyClass, with UserList as its base class, but I wish to override the __add__, append, and extend functions to avoid repetition, so that if items already appear in a list, they will not be added to it. I start by importing UserList from collections, and then I use the following code. It works in part, in that if I try to add, append, or extend with something already in the list, it returns the message 'This item is already in your list' and it is not added. But if I try to add something new, it enters an infinite loop and I have to shut down the window. Any advice will be appreciated. I'm currently learning Python and am quite new to programming.

class MyList(UserList):
    def __int__(self, list):
        self.list=list

    def __add__(self, item):
        if item in self:
            print('This item is already in your list')
        else:
            return self+[item]

    def append(self, item):
        if item in self:
            print('This item is already in your list')
        else:
            return self.append(item)

    def extend(self, item):
        if item in self:
            print('This item is already in your list')
        else:
            return self.extend(item)

Upvotes: 1

Views: 241

Answers (1)

BrenBarn
BrenBarn

Reputation: 251373

Doing self+[item] is adding, so it calls __add__ again, which then tries to call __add__ again, and so on.

You should do super(MyList, self).__add__([item]) to call the base class implementation.

Example:

def append(self, item):
    if item in self:
        print('This item is already in your list')
    else:
        return super(MyList, self).append(item)

Upvotes: 3

Related Questions