Extend __init__ Method When Inheriting a Class
Python
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.
1| class Product(): 2| 3| def __init__(self, name, colour, size, retail_price): 4| 5| self.name = name 6| self.colour = colour 7| self.size = size 8| self.retail_price = retail_price 9| 10| def get_markdown_price(self, discount_rate): 11| return (self.retail_price * (1 - discount_rate)) 12| 13| def __repr__(self): 14| return f"{self.name}. Colour: {self.colour}. Size: {self.size}. Retail Price: ${self.retail_price}" 15| 16| #Top is a type of Product 17| class Top(Product): 18| 19| def __init__(self, name, colour, size, retail_price, sleeve, pocket): 20| #Calls the __init__ method of the base class by using super() to refer to the Product class 21| super().__init__(name, colour, size, retail_price) 22| #Extends the base class Product by adding two additional attributes 23| self.sleeve = sleeve 24| self.pocket = pocket 25| 26| product_15 = Top("Men's Tshirt", "red", "large", 20, "short", True)
147
131
125
118