4. Inheritance - An object oriented pillar!

2 min read

 

Inheritance is one of the pillars of Object-Oriented programming. We will be using Inheritance a lot, especially for Pydantic models. We will soon review pydantic, before that I wanted to quickly cover the basic concepts of Inheritance. If you are already familiar with it, feel free to move to the next section. Before that, I have a question for you.

 

Do you know an object-oriented way to Become Wealthy? Think, think...
Its Inheritance!!
Lame jokes apart. Now, let's quickly jump to the concept of Inheritance.

class Python:
    def __init__(self):
        self.is_cool = True

class FastAPI(Python):
    pass 

f = FastAPI()
print(f.is_cool)

#Output: True

Even though the class FastAPI does not directly have a property named is_cool, Then also we could use f.is_cool. Its because the class FastAPI inherited from the class Python. Any subclass has access to the properties and methods(functions) of the parent class.

This is a very useful feature. I personally use it a lot using a concept called Mixins pattern. This is a very simple pattern in which a child class Inherits from multiple parent classes and uses their feature. For those who are coming from a Django background, you might remember the LoginRequiredMixin!

Unlike, Java, Python also supports multiple Inheritance, As the name suggests, It is a way to have more than one base class. Let's review the below example. StripePayment class is the first parent class and PaypalPayment is the second. If we have the exact same method definition in both the classes, StripePayment's method will get priority as per Method Resolution Order.

class PaypalPayment:
    payment_approved = True

    def is_approved(self):
        return self.payment_approved

class StripePayment:
    payment_approved = False

    def is_approved(self):
        return self.payment_approved


class PaymentVerification(StripePayment,PaypalPayment):
    pass 

payment = PaymentVerification()
print(payment.is_approved())

#Output: False

 

FastAPITutorial

My priority is to help build a production-ready application using FastAPI

I prioritize quality over simplicity. Our challenging approach ensures you're prepared for real-world development.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated with our latest tutorials and resources.

© Copyright 2022-2025 Team FastAPITutorial. All rights reserved.