Python Forum

Full Version: Python - List - Int List
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
Please:
  • Make an effort
  • post your code
  • Ask specific questions
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_list
I 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 ?
I think the hint "As a parent class you can use list." is a good hint. What other methods does list have?
Output:
>>> x = list() >>> print("\n".join(dir(x))) __add__ __class__ __contains__ __delattr__ __delitem__ __dir__ __doc__ __eq__ __format__ __ge__ __getattribute__ __getitem__ __gt__ __hash__ __iadd__ __imul__ __init__ __init_subclass__ __iter__ __le__ __len__ __lt__ __mul__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __reversed__ __rmul__ __setattr__ __setitem__ __sizeof__ __str__ __subclasshook__ append clear copy count extend index insert pop remove reverse sort
Which of these many methods can put a value in the list? append() is a start, but there are others.
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
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 superclass
Making 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.
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 self
Hi, 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.
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]]
Ok, thank you, but I don't know what I have to do with __add__, __setitem__, nothing ?