@
@
@bickford2018-08-26 13:04:55
Django
@bickford, 2018-08-26 13:04:55

What is the correct way to use super()?

Just two questions. First:
When overriding a parent class method, should super() be called first line or last?

def save(self, *args, **kwargs):
    # my code here
    super().save(*args, **kwargs)

or:
def save(self, *args, **kwargs):
    super().save(*args, **kwargs)
    # my code here

?
Second question:
When inheriting a parent class and adding your own logic to one of its methods, which class should be passed to super()?
class Parent:
    def __init__(self, *args, **kwargs):
        pass

class Children(Parent):
    def __init__(self, *args, **kwargs):
        # some code
        super(Parent, self).__init__(*args, **kwargs)

Or:
class Children(Parent):
    def __init__(self, *args, **kwargs):
        # some code
        super(Children, self).__init__(*args, **kwargs)

?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-08-26
_

  1. Depends on the logic of your code. In some cases, the superclass method may not be called at all.
  2. First of all, it should be noted that the requirement to pass a class to a call superonly applies to Python2. In Python3, you can simply super().__init__(*args, **kwargs)But if the class is still passed, then it must be the class in the method of which the call occurs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question