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 self
This 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)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = 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)
Output:
[1, 2, 3]
[1, 2, 3, 4]
Value must be int
[1, 2, 'Oops', 4]
[1, 2, 'Oops', 4, 1.2, 'three', {1: 5}, [6, 7, 9]]