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!
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With