Windows Server In Python, how do you call the super function Object()

mishrajicoder

New Member
Joined
Oct 17, 2022
Messages
6
Code:
class A:
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
       print("hello")

B()  # output: hello
The super function Object() is invoked implicitly in every other language I've worked with. In Python, what does one call it? I expected super(self), but it doesn't work. I read an article on scaler topics that said I needed to use the slightly more verbose version super(containing classname>, self), which is equivalent to super() according to the documentation. Is that right?
 


In Python, the super() function is used to call methods and constructors of the parent class. When working with constructors, super().__init__() is commonly used in the child class to invoke the constructor of the parent class. Here's an example based on your code snippet:

Python:
class A:
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
        super().__init__()  # Calling the constructor of the parent class A
        print("hello")

b = B()  # Output: world hello

In this example:
  • The super().__init__() in class B calls the constructor of class A before printing "hello", giving the output "world hello".
  • The super() function by default references the parent class of the child class in which it is called. This way, you can ensure that the parent class is properly initialized before working with the child class.

So, in Python, super() without any arguments is a standard way to call the parent class methods or constructors, including __init__(). It handles all the details of looking up the inheritance chain and finding the appropriate method to call.
 


Back
Top