1 Upvote

Extend __init__ Method When Inheriting a Class

In this code snippet, we extend the __init__ method of the base class Product when we inherit this class. The Top class is a subclass of Product and it's __init__ method calls the __init__ method of the base class and then extends that __init__ method by declaring two additional attributes; sleeve and pocket.

class Product():
    
    def __init__(self, name, colour, size, retail_price):
        
        self.name = name
        self.colour = colour
        self.size = size
        self.retail_price = retail_price
         
    def get_markdown_price(self, discount_rate):
        return (self.retail_price * (1 - discount_rate))
    
    def __repr__(self):
        return f"{self.name}. Colour: {self.colour}. Size: {self.size}. Retail Price: ${self.retail_price}"

#Top is a type of Product
class Top(Product):
    
    def __init__(self, name, colour, size, retail_price, sleeve, pocket):
        #Calls the __init__ method of the base class by using super() to refer to the Product class
        super().__init__(name, colour, size, retail_price)
        #Extends the base class Product by adding two additional attributes
        self.sleeve = sleeve
        self.pocket = pocket

product_15 = Top("Men's Tshirt", "red", "large", 20, "short", True)

By analyseup - Last Updated Jan. 12, 2022, 12:25 a.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

COMMENTS
RELATED SNIPPETS
Python For Else Loop
Python
General Python

Loop

2
Top Contributors
75