如何覆盖python列表中的init方法? [英] How do I override the init method in python list?
本文介绍了如何覆盖python列表中的init方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要继承 list 类并覆盖 init() 方法以获取参数 a,b .a 应该是我初始化的列表的长度,b 应该是列表中项目之间的步骤.我只是不知道从哪里开始覆盖 init 方法.
I need to inherit list class and override the init() method to take parameters a,b . a should be the lenght of the list I initialise and b should the step between Items in the list. I just don't know where to start with overriding the init method.
def myclass(list):
def __init__(a,b,*args, **kwargs):
pass
我不知道该怎么办.
我已经看到我可以做到这一点:
I have seen I can do this:
class MyClass(list):
def __init__(a,b):
data =[x for x in range(0,a*b,b)]
list.__init__(self,data)
但是我不熟悉python如何实现列表类,例如我如何使用我刚刚通过的列表理解.
But the I am not familiar with how python implements the list class, for instance how do I get to use the list comprehension I just passed.
推荐答案
感谢所有回复的人.意识到我可以通过这种方式实现我想要的:
Thanks to everyone who responded. Realised I could achieve what I wanted to this way:
class myclass(list):
def __init__(self,a,b):
data =[x for x in range(0,a*b,b)]
self.length = len(data)
super(myclass, self).__init__()
self.extend(data)
这篇关于如何覆盖python列表中的init方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文