Python - List - Int List - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Python - List - Int List (/thread-36989.html) |
Python - List - Int List - sophi - Apr-20-2022 Hi, I'm new here and I don't speak English well, but I need a lot of help I have difficult task: Define an IntList () class whose objects will behave the same as objects of the list () class, except that they can only contain integers. When you try to insert (in any way) into such a list something other than an int value, the object throws an exception. As a parent class you can use list. I don't know how to move with it and I didn't find anything on the internet, so I turn here RE: Python - List - Int List - Larz60+ - Apr-20-2022 Please:
RE: Python - List - Int List - sophi - Apr-20-2022 class IntList(list): def __init__(self): self.internal_list = [] def append(self, elem): if not isinstance(elem, int): raise TypeError('x musi byt typu Integer') self.internal_list[len(self.internal_list):] = [elem] def getList(self): return self.internal_listI have that, after a long time :D but I don't know if is the right implementation. Maybe I have problem with print some list. Should I add some others methods ? RE: Python - List - Int List - deanhystad - Apr-20-2022 I think the hint "As a parent class you can use list." is a good hint. What other methods does list have? Which of these many methods can put a value in the list? append() is a start, but there are others.
RE: Python - List - Int List - sophi - Apr-20-2022 class IntList(list): def __init__(self): super().__init__() self.list = [] def __len__(self): return len(self.list) def append(self, elem): if not isinstance(elem, int): raise TypeError('x musí byť typu Integer') self.list[len(self.list):] = [elem] def insert(self, index, value): if not isinstance(value, int): raise TypeError('x musí byť typu Integer') self.list.insert(index, value) def get_list(self): return self.list def __str__(self): return f'{self.list}' def extend(self, listt): if not isinstance(listt, IntList): raise TypeError('Zoznam musí byť typu Integer') z = self.list y = listt.get_list() self.list = z + y print(self.list) return self.list @property def sort(self): x = len(self.list) for i in range(x): for j in range((i + 1), x): if self.list[i] > self.list[j]: l1 = self.list[i] self.list[i] = self.list[j] self.list[j] = l1 return self.list RE: Python - List - Int List - deanhystad - Apr-20-2022 Your class that inherits from list should not have a list attribute. For example, instead of appending to a self.list, your IntList.append() method should look like this: def append(self, elem): if not isinstance(elem, int): raise TypeError('x musí byť typu Integer') super().append(elem) # Call the append for my superclassMaking IntList a proper subclass of list will reduce how much code you need to write. For example, you don't need to write a sort. Sort does not add items to the list, so IntList can inherit the soft method from list. You don't need __init__(), __str_(), __len__(), or get_list() methods either. I think you are still missing some methods that can add/set items in the the list. What about __setitem__() or __add__()? They looks suspicious. I think your extend() method should allow types other than IntList. Check each value, as it is added. RE: Python - List - Int List - sophi - Apr-21-2022 class IntList(list): def __init__(self): super().__init__() def append(self, elem): if not isinstance(elem, int): raise TypeError('x musí byť typu Integer') self[len(self):] = [elem] def insert(self, index, value): if not isinstance(value, int): raise TypeError('x musí byť typu Integer') zoznam = IntList() for x in range(len(self)): posledne = self[x] if x == index: zoznam.append(value) zoznam.append(posledne) self.clear() for x in range(len(zoznam)): self.append(zoznam[x]) if (index >= len(self)): self.append(value) def get_list(self): return self def __str__(self): return self.__repr__() def extend(self, listt): if not isinstance(listt, IntList): raise TypeError('Zoznam musí byť typu Integer') for x in range(len(listt)): self.append(listt[x]) return selfHi, I hope, that this code is ok, because its working :D But I must override methods like __add__, __setitem__ and methods like that, I've tried find out what this methods do, but I don't know. RE: Python - List - Int List - deanhystad - Apr-21-2022 This is not required: def __init__(self): super().__init__()list.__init__() is automatically called if you your subclass does not have an __init__() method. This is not required either. Just use the methods inherited from list. def __str__(self): return self.__repr__()No need for this at all. def get_list(self): return selfThis is overly complicated, def insert(self, index, value): if not isinstance(value, int): raise TypeError('x musí byť typu Integer') zoznam = IntList() for x in range(len(self)): posledne = self[x] if x == index: zoznam.append(value) zoznam.append(posledne) self.clear() for x in range(len(zoznam)): self.append(zoznam[x]) if (index >= len(self)): self.append(value)\ Raise an exception if value is a not a number, else call list.insert(value). Should a 3 lines. And as mentioned before, in extend(listt) you should not force listt to be an IntList, or any kind of list for that matter. Should have to be iterable. According to the docs Quote:list.extend(iterable) Maybe a more concrete example: class IntList(list): def __init__(self, values=None): """Provided so can initalize intlist with values""" super().__init__() if values: self.extend(values) def append(self, value): """Raise exception if bad value, else call superclass method""" if not isinstance(value, int): raise TypeError('Value must be int') super().append(value) def insert(self, index, value): """Raise exception if bad value, else call superclass method""" if not isinstance(value, int): raise TypeError('Value must be int') super().insert(index, value) def extend(self, iterable): """Raise exception if bad value, else call superclass method. See a pattern?""" for value in iterable: if not isinstance(value, int): raise TypeError("All values must be int") super().extend(iterable) x = IntList((1, 2, 3)) print(x) x.append(4) print(x) try: x.insert(4, 'a') except TypeError as msg: print(msg) x[2] = "Oops" # How you going to prevent this??? print(x) x = x + [1.2, "three", {1:5}, [6, 7, 9]] # Another problem? print(x)
RE: Python - List - Int List - sophi - Apr-21-2022 Ok, thank you, but I don't know what I have to do with __add__, __setitem__, nothing ? |