Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding constructors for list in python

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.

like image 682
InfiniteLooper Avatar asked Feb 27 '26 23:02

InfiniteLooper


1 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))
like image 75
James Avatar answered Mar 01 '26 13:03

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!