Once you are comfortable with classes and objects, the next two ideas in object-oriented Python are inheritance and polymorphism. They appear in almost every Django project and in most fresher interviews.
Inheritance: reuse instead of copy
Inheritance lets a new class take the attributes and methods of an existing class.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account):
def add_interest(self, rate):
self.balance += self.balance * rate
SavingsAccount gets deposit() for free and adds its own method. The original class is called the parent (or base) class; the new one is the child.
Overriding and super()
A child class can replace a parent method by defining one with the same name. To extend rather than replace it, call the parent version with super():
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.04):
super().__init__(owner, balance)
self.rate = rate
Forgetting super().__init__() is a common bug: the child object then has no owner or balance.
Polymorphism: one interface, many forms
Polymorphism means different classes respond to the same method call in their own way. If Circle and Square both define area(), you can loop over a mixed list of shapes and call shape.area() without checking each type. Python relies on “duck typing”: if an object has the method you need, you can use it, whatever its class.
Where you will see this in real projects
- Django models inherit from
models.Model. - Django class-based views inherit from
ListView,CreateViewand others, and you override methods such asget_queryset(). - Custom exceptions inherit from
Exception.
A word of caution
Do not build deep chains of inheritance. Two levels are usually enough. If classes only need to share a small helper, a plain function or composition (one object holding another) is often clearer.
Start with Python OOP: classes and objects, then practise by modelling a small bank or library system.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
