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

柔情痞子 提交于 2019-12-24 06:13:55

问题


My question is will the init method of list class calling other method such as append or insert to achieve its functionality.

like:

class test(list):

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

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

I want:

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

but I got:

[1,2,3]

I know I can make it work by overload init itself.

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

Can I just overload some basic value insert method like setitem, so all the insert operation like append, insert will call it, and therefore have that addition effect.

thanks for any suggestion.


回答1:


I've seen another example overriding form collections.MutableSequencethat would let you get this functionality. I'm not sure if this is more convenient than your initial idea, but it will increment any numbers during __init__, append, insert, and extend

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]

See this answer for more information.




回答2:


list.__init__ does not call any overrideable method. It makes a direct, un-overrideable call to the C function that implements the extend method:

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

This is the case for most methods of most Python types implemented in C.



来源:https://stackoverflow.com/questions/44418393/what-is-the-initializing-procedure-underneath-the-init-method-of-python-buil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!