为什么扩展List类在这里不起作用

时间:2019-05-09 04:54:47

标签: python oop subclass

我正在尝试在Python中扩展List类,以便它可以具有size函数。以下是我的代码:

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())

但是,它给出了以下错误:

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

我在这里可以使用的Python列表的类名是什么?

我正在Debian Stable Linux上运行Python 3.5.3。

2 个答案:

答案 0 :(得分:2)

首先,做超级的正确方法是super().__init__()

代码也可以在没有super的情况下工作,正如@ user2357112已经指出的那样,我们在这里甚至不需要构造函数,因为self已经是一个列表,因此将是一个更简单的版本

class Mylist(list):

    def size(self):
        return len(self)

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

输出为

0
3

现在列表的其他操作也可以在这里使用

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]

答案 1 :(得分:0)

在构造函数中设置参数,即可使用list类的默认方法。

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())

输出:

[1, 2, 3, 43]
4

您可以覆盖以下任何一种方法:

>>> 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

这里是Stackoverflow answer by Shital Shah,以详细了解Python中的super()调用。