i'm new to programming so, sorry if what im asking seems rather silly. i understand that i cant have 2 init methods in one class because of function overloading. However, why is it possible that when initializing a subclass, im able to define a new init method, and use the super().init method or the parentclass init method within the subclass init method. i'm just a little confused by the concept of 2 init methods functioning at the same time. i have been stuck on this for a while, please help
class Employee:
emps = 0
def __init__(self,name,age,pay):
self.name = name
self.age = age
self.pay = pay
class Developer(Employee):
def __init__(self,name,age,pay,level):
Employee.__init__(self,name,age,pay)
self.level = level
CodePudding user response:
The “init” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class.
#base class
class State():
def __init__(self):
print("In the state class")
self.state1= "Main State"
#derived class
class HappyState():
def __init__(self):
print("In the happystate class")
self.state2= "Happy State"
super().__init__()
a=HappyState()
print(a.state1)
print(a.state2)
The super() function allows us to avoid using the base class name explicitly. In Python, the super() function is dynamically called as unlike other languages, as it is a dynamic language. The super() function returns an object that represents the parent class. In a subclass, a parent class can be referred to using the super() function. It returns a temporary object of the superclass and this allows access to all of its methods to its child class. While using the super() keyword, we need not specify the parent class name to access its methods.
#base class1
class State():
def __init__(self):
print("In the State class")
self.state1= "Main State"
#base class2
class Event():
def __init__(self):
print("In the Event class")
self.event= "Main Event"
#derived class
class HappyState(State,Event):
def __init__(self):
print("In the happystate class")
super().__init__() #Only calls Base Class 1
a=HappyState()
CodePudding user response:
The super()
function is used to give access to methods and properties of a parent or sibling class
check out: https://www.geeksforgeeks.org/python-super/