Skip to content Skip to sidebar Skip to footer

How Do I Override The Init Method In Python List?

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

Solution 1:

Thanks to everyone who responded. Realised I could achieve what I wanted to this way:

classmyclass(list):
    def__init__(self,a,b):
        data =[x for x inrange(0,a*b,b)]
        self.length = len(data)
        super(myclass, self).__init__()
        self.extend(data)

Solution 2:

You should use super to call the list methods, in this case it will look something like this:

classmyclass(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

Solution 3:

#!/usr/bin/pythonclassmyclass:# use the init to pass the arguments to self/the classdef__init__(self, list, num):
        self.list = list
        self.num = num


    # use this to use the variablesdefuse_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()

Basically uses a class with init to take the list in and do stuff with it.

Post a Comment for "How Do I Override The Init Method In Python List?"