mishrajicoder
New Member
- Joined
- Oct 17, 2022
- Messages
- 6
class A:
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
B() # output: hello
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:
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
super().__init__()
in class B
calls the constructor of class A
before printing "hello", giving the output "world hello".super()
function by default references the parent class of the child class in...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:
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
super().__init__()
in class B
calls the constructor of class A
before printing "hello", giving the output "world hello".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.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.