Python Class Example Using __init__ and __repr__

In this code snippet we create a class called Product that includes attributes for name, colour, size and retail price along with a method for calculating the markdown price given a discount rate. An instance of the Product class is then created called product_12.

To initialise an instance of a class we use an __init__ method. The __init__ method allows us to declare the attributes of a particular instance by passing them as arguments when we create an instance of the class. In this example, each instance of the Product class has attributes name, colour, size and retail_price.

We also use the __repr__ method to return a string whenever an instance of the Product class is printed to the console or notebook cell. It will print out the product attributes we declared in the __init__ method.

class Product():
    def __init__(self, name, colour, size, retail_price):
        #Instance attributes
        self.name = name
        self.colour = colour
        self.size = size
        self.retail_price = retail_price
    #Instance method   
    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}"
product_12 = Product("Men's Tshirt", 'white', "medium", 20)


>> Men's Tshirt. Colour: white. Size: medium. Retail Price: $20
>> $16.0

By analyseup - Last Updated Jan. 10, 2022, 10:34 p.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

Python For Else Loop
General Python


Top Contributors