Yandex

Python Inheritance – Reusing Code



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()
Animal speaks

Explanation:

  • Animal is the parent class with a method speak().
  • Dog is the child class — it uses pass which means "don’t add anything new right now."
  • We create d as a Dog object, but it can still use the speak() method from Animal.

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()
Animal speaks
Dog barks

Explanation:

  • Dog gets speak() from Animal.
  • Dog also has its own method bark().
  • We can use both methods from the Dog object.

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()
Dog says Woof!

Explanation:

  • Dog has its own speak() method.
  • This overrides (replaces) the speak() from the Animal class.
  • So when we call d.speak(), it uses Dog’s version instead.

Why Use Inheritance?

  • Reusability: You don’t need to rewrite the same code.
  • Organized code: Parent classes can hold common code, and child classes can add or change specific behavior.

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