0

Im still alittle unsure how python super works in the below context. If I have the below code running super().values_from_datadict() Is that to say that values_from_datadict() is a function that is available within the parent classes constructor?

Or is this just a function thats available in the parent class in which case. why call .super()? Shoulding it already be available via self.

class MyWidget(Select2TagWidget):

    def value_from_datadict(self, data, files, name):
        values = super().value_from_datadict(data, files, name)
        return ",".join(values)
foxRun28
  • 13
  • 4
  • 1
    Does this answer your question? [how to refer to a parent method in python?](https://stackoverflow.com/questions/9347406/how-to-refer-to-a-parent-method-in-python) – Brian61354270 Mar 06 '23 at 17:29
  • _"Or is this just a function thats available in the parent class"_ Yes. _"why call .super()? Shoulding [sic] it already be available via self."_ If you call `self.f()` from within `f()`, you'll end up recursively calling the same method. `super` is needed to refer to the _parent_ class' `f`. In this case, `super().value_from_datadict(...)` is equivalent to calling `Select2TagWidget.value_from_datadict(...)` – Brian61354270 Mar 06 '23 at 17:32

2 Answers2

0

If you create a function that already exists in the parent class, you overwrite that function. This doesn't always use the parent class's original function, but in this particular case, you are overwriting the value_from_datadict function with a new function that uses the parent's original value_from_datadict. You don't want to use self.value_from_datadict because then you would be recursively calling the child's function. The intent in this case is to use the parent's value_from_dict via the super() and then modify its output for the child's value_from_dict output.

Michael Cao
  • 2,278
  • 1
  • 1
  • 13
0

super is a type whose sole purpose is to delegate name lookup to an appropriate class.

In this case,

class MyWidget(Select2TagWidget):

    def value_from_datadict(self, data, files, name):
        values = super().value_from_datadict(data, files, name)
        return ",".join(values)

the instance created by super is little more than a wrapper around both MyWidget and self. Its __getattribute__ method uses type(self).mro() == [MyWidget, Select2TagWidget, ..., object] to find the first class after MyWidget that has a value_from_datadict attribute, then returns that attribute's value.

chepner
  • 497,756
  • 71
  • 530
  • 681