0
0
Pythonprogramming~5 mins

Extending parent behavior in Python

Choose your learning style9 modes available
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.
You have a basic class and want a new class that adds extra features.
You want to keep the original behavior but also do something additional.
You want to reuse code from a parent class and add your own steps.
You want to change how a method works but still use the original method inside it.
Syntax
Python
class ChildClass(ParentClass):
    def method(self):
        super().method()  # call parent method
        # add extra behavior here
Use super() to call the parent class method inside the child class.
This lets you keep the parent's behavior and add new things after or before it.
Examples
Dog keeps Animal's speak and adds its own bark.
Python
class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        super().speak()
        print("Dog barks")
Car adds a check before starting the vehicle.
Python
class Vehicle:
    def start(self):
        print("Vehicle started")

class Car(Vehicle):
    def start(self):
        print("Car checks seatbelt")
        super().start()
Sample Program
Friend uses Person's greet and adds a friendly question.
Python
class Person:
    def greet(self):
        print("Hello!")

class Friend(Person):
    def greet(self):
        super().greet()
        print("How are you?")

f = Friend()
f.greet()
OutputSuccess
Important Notes
Calling super() is important to keep the original behavior.
You can call super() before or after your extra code depending on what you want.
If you forget super(), the parent method won't run.
Summary
Extending parent behavior means adding to what the parent class does.
Use super() to run the parent method inside the child method.
This helps reuse code and add new features without rewriting everything.