python内置列表的__init__方法下面的初始化过程是什么 [英] What is the initializing procedure underneath the __init__ method of python built-in list

查看:296
本文介绍了python内置列表的__init__方法下面的初始化过程是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是列表类的 init 方法是否将调用其他方法(例如append或insert)来实现其功能.

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

喜欢:

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 本身来使其工作.

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

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

我可以重载一些基本值插入方法(如 setitem ),所以所有诸如insert,insert之类的插入操作都将调用它,因此具有加法效果.

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.

感谢您的任何建议.

推荐答案

我已经看到了另一个替代表格collections.MutableSequence的示例,该示例可以让您获得此功能.我不确定这是否比您的最初想法更方便,但是它会在__init__appendinsertextend

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.

这篇关于python内置列表的__init__方法下面的初始化过程是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆