Python Forum

Full Version: super() in class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
in code:
# from: https://roocket.ir/discuss/%D8%B9%D9%85%D9%84%DA%A9%D8%B1%D8%AF-
# super-%D8%AF%D8%B1-%D8%A7%D8%B1%D8%AB-%D8%A8%D8%B1%DB%8C-%D8%A7%D8%B2-
# %DA%86%D9%86%D8%AF-%DA%A9%D9%84%D8%A7%D8%B3-%D8%AF%D8%B1-
# %D9%BE%D8%A7%DB%8C%D8%AA%D9%88%D9%86

# usage of super()

class First():
    def __init__(self):
        print ("first")
 
class Second(First):
    def __init__(self):
        super().__init__()
        print ("second")
 
class Third(First):
    def __init__(self):
        super()
        print ("third")
 
class Fourth(Second ,Third):
    def __init__(self):
        super().__init__()
        print ("that's it")
 
Fourth()
# output is:
"""
third
second
that's it
"""

class Third2(First):
    def __init__(self):
        super().__init__()
        print ("third")


class Fourth2(Second ,Third2):
    def __init__(self):
        super().__init__()
        print ("that's it")
 
Fourth2()
# output is:
"""
first  
third  
second  
that's it
"""
as you can see in Second class(line 14) there is super().__init__ and in Third class(line 19) there is super().
what is super() and what is it used for?
what is the difference between the two above-mentioned lines?
I searched and read some on the net for super() and in Python documentation but I did not get anything of them and I did not get a suitable explanation about super(). plz, explain about it.
in some codes I saw such as super().c(). i think c() is a method.( code is long, so I did not import it here)
what is it? again, explanation
thanks
From the docs

Quote:There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).