When do I need to use super()?

Which INHERITS from list. No comment on the rest.

2 Likes

Hello,
can you tell if my understand ing is true ?

when we use self in inherited class and use it inside method that is already present in parent class super() [ I think it should be a function returns class because we use DOT notation on it ??? ] instruct a interpreter : Hey I’m going to modify a method we have already in parent class but I need you to copy a parameters i give to super() to you copy them for me and save me from typing all them again ?

also we could have same functionality by defining new iter method instead of using super() keyword copy and paste all variables and things inside parent class iter method and have same functionality if use super() It just copy what we tell for us for our new re defined method in this case iter

hey @mtf,
How does this self refers to the the list, just because the parent class is list and there is no other parameters?

If we instantiate a SortedList we are given an empty list. The instance object is self, the context or owner object.

class SortedList(list):
  def __init__(self, value):
    self = value
    self.sort()
    print(self)
  def append(self, value):
    super().append(value)
    self.sort()
sorted_list = SortedList([4, 1, 5])
print(sorted_list)

output:[1, 4, 5]

what’s wrong with this code why it is giving output a blank list .
but when i am using super().init(value) instead of self= value then it is giving the right answer.
can anyone explain it to me what’s the difference between both and what i am not getting right?

Hi everyone!

Q1:
I tried to keep a copy the list received as argument at the instantiation.
For that reason I created two class variables:

  1. list_s = the sorted one.
  2. list_u = the unsorted one.
    The problem is that after calling the sort() method both list_s and list_u get sorted.

How can I limit the action of sort() to list_s only. At the end, it is about handling variables of the same type with independence.

Thanks!

class SortedList(list):

  def __init__(self, lst):
    super().__init__(lst)
    self.list_s = lst
    self.list_u = lst

    # Before sort()
    print("Before sort(), list_s: {sorted} list_u: {unsorted}".format(sorted=self.list_s, unsorted=self.list_u))

    self.list_s.sort( )
    
    # Before after()
    print("After sort(), list_s: {list1} list_u: {list2}".format(list1=self.list_s, list2=self.list_u))

object_sorted = SortedList([7, 9, 5, 3])