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)
Aucun commentaire:
Enregistrer un commentaire