Python Class Example Using __init__ and __repr__

Python

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.

 1|  class Product():
 2|      
 3|      #Initilisation
 4|      def __init__(self, name, colour, size, retail_price):
 5|          
 6|          #Instance attributes
 7|          self.name = name
 8|          self.colour = colour
 9|          self.size = size
10|          self.retail_price = retail_price
11|          
12|      #Instance method   
13|      def get_markdown_price(self, discount_rate):
14|          return (self.retail_price * (1 - discount_rate))
15|      
16|      def __repr__(self):
17|          return f"{self.name}. Colour: {self.colour}. Size: {self.size}. Retail Price: ${self.retail_price}"
18|      
19|  product_12 = Product("Men's Tshirt", 'white', "medium", 20)
20|  
21|  print(product_12)
22|  print(f"${product_12.get_markdown_price(0.2)}")
23|  
24|  >> Men's Tshirt. Colour: white. Size: medium. Retail Price: $20
25|  >> $16.0
Did you find this snippet useful?

Sign up for free to to add this to your code library