Overriding constructors for list in python

Viewed 189

Let's say I want to implement some list class in python with extra structure, like a new constructor. I wrote:

import random

class Lis(list):
    def __init__(self, n):
        self = []
        for i in range(n):
            self.append(random.randint(0, 30))

Now doing Lis(3) gives me an empty list. I don't know where I did it wrong.

2 Answers

You are overriding the object with self = []

try the following

import random

class Lis(list):
    def __init__(self, n):
        for i in range(n):
            self.append(random.randint(0, 30))

if you want to return a list from object call

class MyClass(object):
    def __init__(self):
        print "never called in this case"
    def __new__(cls):
        return [1,2,3]

obj = MyClass()
print(obj)

How to return a value from __init__ in Python?

or if you want an modified object try:

class MyClass:
    def __getitem__(self, key):
        not_self = []
        for i in range(n):
            not_self.append(random.randint(0, 30))
        return not_self
myobj = MyClass()

myobj[3] #Output: 6

How to override the [] operator in Python?

I am not sure if using self like you did is healthy.

Related