python内置列表的__init__方法下面的初始化过程是什么

What is the initializing procedure underneath the __init__ method of python built-in list

我的问题是列表 class 的 init 方法是否会调用其他方法(例如追加或插入)来实现其功能。

喜欢:

class test(list):

def __init__(self,values):
    super().__init__()

def append(self, value):
    self.append(value + 1)

我要:

x = test([1,2,3])
x
[2,3,4]

但我得到了:

[1,2,3]

我知道我可以通过重载 init 本身来让它工作。

def __init__(self,values):
    super().__init__([x+1 for x in values])

我能不能只重载一些基本的值插入方法,比如setitem,这样所有的插入操作,比如append,insert都会调用它,从而起到加法的效果。

感谢任何建议。

list.__init__ 不调用任何可覆盖的方法。它对实现 extend 方法的 C 函数生成 direct, un-overrideable call

if (arg != NULL) {
    PyObject *rv = listextend(self, arg);
    if (rv == NULL)
        return -1;
    Py_DECREF(rv);
}

在 C 中实现的大多数 Python 类型的大多数方法都是这种情况。

我看过另一个覆盖表单的示例 collections.MutableSequence,它可以让您获得此功能。我不确定这是否比您最初的想法更方便,但它会在 __init__appendinsertextend[=17= 期间增加任何数字]

class IncList(collections.MutableSequence):
    def __init__(self, int_list):
        self._list = []
        for el in int_list:
            self.append(el)

    def __len__(self): return len(self._list)
    def __getitem__(self, item): return self._list[item]
    def __delitem__(self, item): del self._list[item]

    def __setitem__(self, index, value):
        self._list[index] = value + 1

    def insert(self, index, value):
        self._list.insert(index, value + 1)

    def __str__(self):
        return str(self._list)

    def __repr__(self):
        return "%s(%r)" % (self.__class__, self._list)


> l = IncList([1, 2, 3])
> print(l)
[2, 3, 4]
> l.append(4)
> print(l)
[2, 3, 4, 5]
> l[0] = 0
> print(l)
[1, 3, 4, 5]
> l.extend([5, 6])
> print(l)
[1, 3, 4, 5, 6, 7]
> l.insert(1, 1)
> print(l)
[1, 2, 3, 4, 5, 6, 7]

有关详细信息,请参阅 this answer