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.
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.
A class is like a template or blueprint. It defines how something should behave. We use classes to create objects.
Inheritance means that one class (called the child) can use the code of another class (called the parent).
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
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."d
as a Dog object, but it can still use the speak()
method from Animal.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
Dog
gets speak()
from Animal.Dog
also has its own method bark()
.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!
Dog
has its own speak()
method.speak()
from the Animal class.d.speak()
, it uses Dog’s version instead.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!
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.