Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to initialise a OOP List with some values already known?

Tags:

python

oop

I am trying to get into Object Oriented Programming but am getting stuck on something which is probably very simple. I want to have an object which is a list, but which starts with having some values passed into it.

Example:

class superList(list):
    def __init__(self,startingValues):
        self = startingValues

myList = superList([1,2,3])
myList.append(4)
print(myList)

I want the output of this to be [1,2,3,4]. If anyone could help, I would be very thankful!

like image 936
JimmyCarlos Avatar asked Jan 29 '23 21:01

JimmyCarlos


1 Answers

Assigning to self isn't useful; you are just assigning to a local name that goes away after __init__ returns. Instead, you need to use __new__, and call the parent's class's __new__ method.

class SuperList(list):
    def __new__(cls, starting_values):
        return list.__new__(cls, starting_values)

Another approach is to use __init__, and just append the values in place:

class SuperList(list):
    def __init__(self, starting_values):
        self.extend(starting_values)

As pointed out in the comments, though, you would get the exact same result by not overriding either method:

class SuperList(list):
    pass

because you aren't doing anything except invoking parent-class behavior in either method. In the absence of a defined SuperList.__new__, for example, SuperList([1,2,3]) just calls list.__new__(SuperList, [1,2,3]) anyway.

More interesting is when the class itself (at least, in part) determines behavior beyond using the values passed by the caller. For example:

class SuperList(list):
    def __init__(self, starting_values):
        self.extend([2*x for x in starting_values])

or

    def __init__(self):
        self.extend([1,2,3])
like image 120
chepner Avatar answered Feb 07 '23 17:02

chepner