The reason we use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO)
xxxxxxxxxx
class ChildB(Base):
def __init__(self):
super().__init__()
In Python 2, we were required to call super like this with the defining class's name and self, but we'll avoid this from now on because it's redundant, slower (due to the name lookups), and more verbose (so update your Python if you haven't already!):
super(ChildB, self).__init__()
xxxxxxxxxx
# It's kinda hard to explain this just by code.
# So I'll provide a link to a pretty good explanation of it.
https://www.pythonforbeginners.com/super/working-python-super-function
xxxxxxxxxx
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
xxxxxxxxxx
class ParentClass:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
class ChildClass(ParentClass):
def __init__(self, parameter1, parameter2, parameter3):
# Calling the parent class's __init__ method using super()
super().__init__(parameter1, parameter2)
self.parameter3 = parameter3
def print_parameters(self):
print(f"Parameter 1: {self.parameter1}")
print(f"Parameter 2: {self.parameter2}")
print(f"Parameter 3: {self.parameter3}")
# Creating an instance of the ChildClass
child_obj = ChildClass("Value 1", "Value 2", "Value 3")
# Calling the print_parameters method of the ChildClass
child_obj.print_parameters()
xxxxxxxxxx
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}!")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Calling the parent class constructor
self.age = age
def greet(self):
super().greet() # Calling the greet method of the parent class
print(f"You are {self.age} years old!")
child = Child("Alice", 10)
child.greet()
xxxxxxxxxx
class SuperClass:
def __init__(self):
pass
def example_method(self):
print('Hello, World!')
class SubClass(SuperClass):
def __init__(self):
pass
c = SubClass()
c.example_method()