Python: Inheritance

NOTES

If no base class is defined for a class, then it is a subclass of “object“.

So, not defining base class is equivalent to – class MyClass(object)

NOTES

If a method implementation in the base class serves our purpose, and is sufficient for our requirement, then we do not need to reimplement it in a subclass.

Inherit from Single Class

class BigBoxParent:
    def myParentMethOne(self):
        print("my Parent Meth One")
        
    def myParentMethTwo(self):
        print("my Parent Meth Two")
        
class BigBoxChild(BigBoxParent):
    def myChildMethodOne(self):
        print("My Child Method One")
        

child_obj = BigBoxChild()
child_obj.myChildMethodOne()
child_obj.myParentMethOne()

print(dir(child_obj))
Python

Output:

My Child Method One
my Parent Meth One


['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
'__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 
'myChildMethodOne', 'myParentMethOne', 'myParentMethTwo']
Plaintext

Inherit from Multiple Classes

class BigBoxParent:
    def myParentMethOne(self):
        print("my Parent Method One")
        
    def myParentMethTwo(self):
        print("my Parent Method Two")
        
class NewParent:
    def newParentMethOne(self):
        print("new Parent Method one")
        
    def newParentMethTwo(self):
        print("new Parent Method Two")
        
class BigBoxChild(BigBoxParent, NewParent):
    def myChildMethodOne(self):
        print("My Child Method One")
        

child_obj = BigBoxChild()
child_obj.myChildMethodOne()
child_obj.myParentMethOne()
child_obj.newParentMethTwo()

print(dir(child_obj))
Python

Output:

My Child Method One
my Parent Method One
new Parent Method Two


['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', 'myChildMethodOne', 'myParentMethOne', 'myParentMethTwo', 
'newParentMethOne', 'newParentMethTwo']
Plaintext

__init__ Execution in Inheritance

class BigBoxParent:
    def __init__(self) -> None:
        print("BigBoxParent __init__")

    def myParentMethodOne(self) -> None:
        print("my Parent Method One")

    def myParentMethTwo(self) -> None:
        print("my Parent Method Two")


class BigBoxChild(BigBoxParent):
    def __init__(self) -> None:
        super().__init__()
        print("BigBoxChild __init__")

    def myChildMethodOne(self) -> None:
        print("my Child Method One")


child_obj = BigBoxChild()
child_obj.myChildMethodOne()
child_obj.myParentMethodOne()
Python

Output:

BigBoxParent __init__
BigBoxChild __init__

my Child Method One
my Parent Method One
Plaintext
class BigBoxParent:
    def __init__(self):
        print("BigBoxParent __init__")

    def myParentMethOne(self):
        print("my Parent Method One")
        
    def myParentMethTwo(self):
        print("my Parent Method Two")
        
class NewParent:
    def __init__(self):
        print("NewParent __init__")
        
    def newParentMethOne(self):
        print("new Parent Method one")
        
    def newParentMethTwo(self):
        print("new Parent Method Two")
        
class BigBoxChild(BigBoxParent, NewParent):
    def __init__(self):
        NewParent.__init__(self)
        print("BigBoxChild __init__")
        
    def myChildMethodOne(self):
        print("my Child Method One")
        

child_obj = BigBoxChild()
child_obj.myChildMethodOne()
child_obj.myParentMethOne()
child_obj.newParentMethTwo()
Python

Output:

NewParent __init__
BigBoxChild __init__

My Child Method One
my Parent Method One
new Parent Method Two
Plaintext

Examples

Let’s give some examples of clear usage of inheritance in Python.

Example #1: Product Classes

class Product:
    def __init__(self, id: int, name: str, price: float, description: str) -> None:
        self.id = id
        self.name = name
        self.price = price
        self.description = description

    def get_details(self) -> str:
        return f"Product ID: {self.id}, Name: {self.name}, Price: {self.price}, Description: {self.description}"


class PhysicalProduct(Product):
    def __init__(
        self,
        id: int,
        name: str,
        price: float,
        description: str,
        weight: float,
        dimensions=str,
    ) -> None:
        super().__init__(id, name, price, description)

        self.weight = weight
        self.dimensions = dimensions

    def get_shipping_details(self) -> str:
        return f"Weight: {self.weight} kg, Dimensions: {self.dimensions} cm"


# Usage example

physical_product = PhysicalProduct(
    1, "SWH-30G21", 99.99, "Sonic Wireless Headphones", 1.5, "30 x 20 x 5"
)

print(physical_product.get_details())

print(physical_product.get_shipping_details())

print("ID: ", physical_product.id)
print("Weight: ", physical_product.weight)
print("Dimensions: ", physical_product.dimensions)
print("Price: ", physical_product.price)
Python

Output:

Product ID: 1, Name: SWH-30G21, Price: 99.99, Description: Sonic Wireless Headphones
Weight: 1.5 kg, Dimensions: 30 x 20 x 5 cm
ID:  1
Weight:  1.5
Dimensions:  30 x 20 x 5
Price:  99.99
Plaintext

Example #2: Physical and Digital Products

class Product:
    def __init__(self, id: int, name: str, price: float, description: str):
        self.id: int = id
        self.name: str = name
        self.price: float = price
        self.description: str = description

    def get_details(self) -> str:
        return f"Product ID: {self.id}, Name: {self.name}, Price: {self.price}, Description: {self.description}"


class PhysicalProduct(Product):
    def __init__(
        self,
        id: int,
        name: str,
        price: float,
        description: str,
        weight: float,
        dimensions: str,
    ):
        super().__init__(id, name, price, description)
        self.weight: float = weight
        self.dimensions: str = dimensions

    def get_shipping_details(self) -> str:
        return f"Weight: {self.weight} kg, Dimensions: {self.dimensions} cm"


class DigitalProduct(Product):
    def __init__(
        self,
        product_id: int,
        name: str,
        price: float,
        description: str,
        size: float,
        link: str,
    ):
        super().__init__(product_id, name, price, description)
        self.size: float = size
        self.link: str = link

    def get_download_details(self) -> str:
        return f"File Size: {self.size} MB, Download Link: {self.link}"


# Usage example

# Define physical product
physical_product = PhysicalProduct(
    id=1,
    name="SWH-30G21",
    price=99.99,
    description="Sonic Wireless Headphones",
    weight=1.5,
    dimensions="30 x 20 x 5",
)

print(physical_product.get_details())
print(physical_product.get_shipping_details())
print("ID: ", physical_product.id)
print("Weight: ", physical_product.weight)
print("Dimensions: ", physical_product.dimensions)
print("Price: ", physical_product.price)

# Define digital product
digital_product = DigitalProduct(
    product_id=2,
    name="DL-2209",
    price=7.50,
    description="BigBoxCode Premium Python tutorial",
    size=20,
    link="https://bigboxcode.com/dl-2209",
)

print(digital_product.get_details())
print(digital_product.get_download_details())
print("ID: ", digital_product.id)
print("Size: ", digital_product.size)
print("Link: ", digital_product.link)
Python

Output:

Product ID: 1, Name: SWH-30G21, Price: 99.99, Description: Sonic Wireless Headphones
Weight: 1.5 kg, Dimensions: 30 x 20 x 5 cm
ID:  1
Weight:  1.5
Dimensions:  30 x 20 x 5
Price:  99.99


Product ID: 2, Name: DL-2209, Price: 7.5, Description: BigBoxCode Premium Python tutorial
File Size: 20 MB, Download Link: https://bigboxcode.com/dl-2209
ID:  2
Size:  20
Link:  https://bigboxcode.com/dl-2209
Plaintext

Example #3: Physical Product with Tax and Discount

class Product:
    def __init__(self, id: int, name: str, price: float, description: str):
        self.id: int = id
        self.name: str = name
        self.price: float = price
        self.description: str = description

    def get_details(self) -> str:
        return f"Product ID: {self.id}, Name: {self.name}, Price: {self.price}, Description: {self.description}"


class Discount:
    def __init__(self, discount: float):
        self.discount: float = discount

    def calculate_discount(self, price: float) -> float:
        return price * self.discount / 100


class Tax:
    def __init__(self, tax_rate: float):
        self.tax_rate: float = tax_rate

    def calculate_tax(self, price: float) -> float:
        return price * self.tax_rate / 100


class PhysicalProduct(Product, Tax, Discount):
    def __init__(
        self,
        id: int,
        name: str,
        price: float,
        description: str,
        weight: float,
        dimensions: str,
        tax: float = 0,
        discount: float = 0,
    ):
        Product.__init__(self, id, name, price, description)
        Tax.__init__(self, tax)
        Discount.__init__(self, discount)

        self.weight: float = weight
        self.dimensions: str = dimensions

    def get_shipping_details(self) -> str:
        return f"Weight: {self.weight} kg, Dimensions: {self.dimensions} cm"

    def get_tax(self) -> float:
        return self.calculate_tax(self.price)

    def get_discount(self) -> float:
        return self.calculate_discount(self.price)

    def get_final_price(self) -> float:
        return self.price + self.get_tax() - self.get_discount()


# Usage example

# Define physical product
physical_product = PhysicalProduct(
    id=1,
    name="SWH-30G21",
    price=99.99,
    description="Sonic Wireless Headphones",
    weight=1.5,
    dimensions="30 x 20 x 5",
    tax=8.5,
    discount=5,
)

print(physical_product.get_details())

print(physical_product.get_shipping_details())

print("ID: ", physical_product.id)
print("Weight: ", physical_product.weight)
print("Dimensions: ", physical_product.dimensions)
print("Price: ", physical_product.price)
print("Tax: ", physical_product.get_tax())
print("Discount: ", physical_product.get_discount())
print("Final Price: ", physical_product.get_final_price())
Python

Output:

Product ID: 1, Name: SWH-30G21, Price: 99.99, Description: Sonic Wireless Headphones
Weight: 1.5 kg, Dimensions: 30 x 20 x 5 cm
ID:  1
Weight:  1.5
Dimensions:  30 x 20 x 5

Price:  99.99
Tax:  8.49915
Discount:  4.9995
Final Price:  103.48965
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.