Introduction
Sometimes you want a new thing to do everything the old thing does, plus a little more. Extending parent behavior helps you add new actions while keeping the old ones.
Jump into concepts and practice - no test required
class ChildClass(ParentClass): def method(self): super().method() # call parent method # add extra behavior here
super() to call the parent class method inside the child class.class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def speak(self): super().speak() print("Dog barks")
class Vehicle: def start(self): print("Vehicle started") class Car(Vehicle): def start(self): print("Car checks seatbelt") super().start()
class Person: def greet(self): print("Hello!") class Friend(Person): def greet(self): super().greet() print("How are you?") f = Friend() f.greet()
super() is important to keep the original behavior.super() before or after your extra code depending on what you want.super(), the parent method won't run.super() to run the parent method inside the child method.super() do in a child class method?super()super() is used to call a method from the parent class inside a child class method.greet inside a child class method in Python?super() is a function and must be called with parentheses before accessing methods.super().greet(), not super.greet() or others.class Parent:
def greet(self):
print('Hello from Parent')
class Child(Parent):
def greet(self):
super().greet()
print('Hello from Child')
c = Child()
c.greet()super().greet() first, which prints 'Hello from Parent'.class Parent:
def show(self):
print('Parent show')
class Child(Parent):
def show(self):
super.show()
print('Child show')super.show() which is incorrect syntax; super() must be called as a function.super().show() to properly call the parent method.calculate so that the child class adds 10 to the parent's result. Which code correctly does this?
class Parent:
def calculate(self):
return 5
class Child(Parent):
def calculate(self):
# Fill here
super().calculate() inside the child method.super().calculate() + 10.