3

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.

petrov.aleksandr
  • 622
  • 1
  • 5
  • 24
InfiniteLooper
  • 324
  • 2
  • 12

2 Answers2

2

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))
James
  • 361
  • 2
  • 8
0

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.

Furkan
  • 352
  • 3
  • 12