python中def _init_是什么意思,python内置列表的__init__方法下面的初始化过程是什么...

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值