Super() and append

In this code

class SortedList(list):
  def append(self, value):

When you say


What are you appending value too? It looks like your just calling append on nothing. This is python.



That line calls the append() method that is defined in the parent class (list in here), Implicitly it still will have passed the instance from which it’s being called. More explicitly that line would look like:

super(SortedList, self).append(value)

super() will find the appropriate parent method and then implicitly pass self to it, along the specified value argument.

1 Like

So it is appending value to self?

So for this particular case you can only use super(). You cant invoke the parent class directly like this:


Because list is not an instance. So basically super is the only way to do it in this code?

I think saying that is close enough. I’m not entirely sure how internally list is keeping elements, but the point is value is appended in the self instance.

In here list.append(self, value) also should work, again passing the instance explicitly.

I thought that append can only take one argument tho. The one that it wants to append. Maybe you can explain how adding self in as an argument works. As best and in depth as you can or is possible.

Append is not a dunder function right? So it should not take self as an argument

When you are using it you usually pass just one argument, yes.

Taking for example class from your first post, using it will look something like:

sorted_list = SortedList()

Just single argument is passed, while in the method definition there’s self and value parameters. self argument is omitted, because that is handled by python. When sorted_list.append(3) is called, python is implicitly passing the instance as the self argument. This is how it is with a specific instance.
On the other hand when list.append(self, value) is called python can’t automatically pass instance to the method, as this is class being called, not an instance. So self as instance needs to be passed explicitly.

Generally all instance methods should have at least one argument, which for instance is by convention called self. Being dunder function or not is irrelevant here. If method isn’t supposed to later take any additional arguments it still requires self.
There are actually two exceptions - static methods and class methods. Class methods take class argument instead of instance and static method take neither. But that is even further away from your question.

1 Like

Ok thanks so much for clearing that up. I can tell you know alot about this subject. Howcome nowhere I look on google do they show self being passed into append? Nowhere do they explain what you just explained…

It’s just a very specific example, more general explanations (or using different examples) of these concepts are definitely out there in various places.