Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

Python Inheritance – Reusing Code the Easy Way



In programming, Inheritance is a way to make one class (a blueprint for an object) get all the features (code) of another class — so you don't have to repeat yourself!

This helps us reuse code and build on top of existing code instead of starting from scratch.

What Is a Class?

A class is like a template or blueprint. It defines how something should behave. We use classes to create objects.

What Is Inheritance?

Inheritance means that one class (called the child) can use the code of another class (called the parent).

Example 1: Basic Inheritance

Let’s say we have a general class called Animal that has a function speak(). We can create a class Dog that inherits everything from Animal.

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    pass

d = Dog()
d.speak()
    

Output:

Animal speaks

Explanation:

Example 2: Child Adds Its Own Method

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Dog barks")

d = Dog()
d.speak()
d.bark()
    

Output:

Animal speaks
Dog barks

Explanation:

Example 3: Child Overrides Parent Method

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog says Woof!")

d = Dog()
d.speak()
    

Output:

Dog says Woof!

Explanation:

Why Use Inheritance?

Conclusion

Inheritance helps us build smarter programs by reusing and extending code. Once you understand how a child class can use and even change what it gets from a parent class, you’ll be able to organize your Python programs better and avoid repeating yourself.

Don’t worry if this feels new — with practice, inheritance will feel natural!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M