0

I am trying to extend List class in Python so that it can have a size function. Following is my code:

class Mylist(List):
    self.slist = []
    def __init__(self, slist=[]):
        self.slist = slist
        super(slist)
    def size(self):
        return len(slist)

ll = Mylist([1,2,3])
print(ll.size())

However, it is giving following error:

$ python3 mylist.py 
Traceback (most recent call last):
  File "mylist.py", line 1, in <module>
    class Mylist(List):
NameError: name 'List' is not defined

What is the class name of Python List that I can use here?

I am running Python 3.5.3 on Debian Stable Linux.

rnso
  • 23,686
  • 25
  • 112
  • 234
  • 5
    Python is case sensitive: the built-in data type is `list`, not `List`. – FMc May 09 '19 at 04:56
  • Apparently `super(slist)` also should be `super=slist` ? Or should I use super.__init__ ? Is any of these needed at all? – rnso May 09 '19 at 04:59
  • `super(slist)` is wrong (it looks like you're trying to use Java syntax or something), but `super=slist` is also wrong; `super=slist` just assigns to a local variable named `slist`. It's `super().__init__(superclass constructor arguments go here)`. – user2357112 May 09 '19 at 05:01
  • How about super.__init__ ? Can I avoid super altogether? – rnso May 09 '19 at 05:01
  • 2
    Everything with `self.slist` is wrong, too; `self` is already a list. The only thing this class needs in the body is `def size(self): return len(self)`, but really, this class shouldn't exist at all. – user2357112 May 09 '19 at 05:06
  • As user2357112 already mentioned, just adding the `size` function to the extended class will be enough @rnso – Devesh Kumar Singh May 09 '19 at 06:14

2 Answers2

3

To begin with, The correct way of doing super is super().__init__()

Also the code works without super, and as @user2357112 already pointed out, we don't even need a constructor here, since self is already a list, so a much simpler version would be

class Mylist(list):

    def size(self):
        return len(self)

print(Mylist([1,2,3]).size())
print(Mylist([]).size())

The output is

0
3

And now the other operations of list can also be used here

x = Mylist([1,2,3])
x.append(4)
print(x)
#[1, 2, 3, 4]
x.extend([5,6,7])
print(x)
#[1, 2, 3, 4, 5, 6, 7]
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

Set the parameter in constructor and you can use the default methods of list class.

class Mylist(list):
    def __init__(self, slist=[]):
        super(Mylist, self).__init__(slist)
    def size(self):
        return super(Mylist, self).__len__()

ll = Mylist([1,2,3])
ll.append(43)
print(ll)
print(ll.size())

Output:

[1, 2, 3, 43]
4

You can override any of the following methods:

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

Here is a Stackoverflow answer by Shital Shah to learn more about super() calls in Python.

arshovon
  • 13,270
  • 9
  • 51
  • 69