我需要继承list类并重写init()方法以获取参数a,b。A应该是我初始化的列表的长度,b应该是列表中项之间的步骤。我只是不知道从哪里开始重写init方法。
def myclass(list):
def __init__(a,b,*args, **kwargs):
pass我不知道该怎么克服这件事。
我见过我能做到:
class MyClass(list):
def __init__(a,b):
data =[x for x in range(0,a*b,b)]
list.__init__(self,data)但是,我不熟悉python如何实现列表类,例如,如何使用我刚刚传递的列表理解。
发布于 2016-11-01 13:36:25
感谢每一个回复的人。意识到我可以用这种方式实现我想要的:
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)发布于 2016-11-01 02:58:11
您应该使用超级调用list方法,在这种情况下,它将如下所示:
class myclass(list):
def __init__(self, a, b, *args, **kwargs):
super(myclass, self).__init__() # this will call the list init
# do whatever you need with a and b
l = myclass(10, 0)
l.append(10) # this will calls list append, since it wasn't overriden.
print l发布于 2016-11-01 03:44:22
#!/usr/bin/python
class myclass:
# use the init to pass the arguments to self/the class
def __init__(self, list, num):
self.list = list
self.num = num
# use this to use the variables
def use_the_stuff(self):
#prints the item in the given place
# i.e in a list of ["A","B","C"]
# if self.num is 0, then A will be printed.
print self.list[self.num]
list_abc = ["A", "B", "C"]
myclass(list_abc, 2).use_the_stuff()基本上使用一个带有init的类来获取列表并使用它做一些事情。
https://stackoverflow.com/questions/40353458
复制相似问题