How to use __str__ function to return a string representation of a class

Advertisements

I have been tasked with creating an inventory manager in python, and one of the required is to define the following function within the class:

__str__ – This function returns a string representation of a
class.

The class refers to a file (inventory.txt) which has the following format:
Country,Code,Product,Cost,Quantity

my code thus far is as follows:

# Creating the class:

class Shoes():

    # Constructor:
    def __init__(self,country,code,product,cost,quantity):
        self.country = country
        self.code = code
        self.product = product
        self.cost = cost
        self.quantity = quantity
    
    # Methods:
    def get_cost():

        inventory = open('inventory.txt','r')
        inventory_list = inventory.readlines()

        code = input("What is the code of the product:")

        for line in inventory_list:
            split_lines = line.split(",")
            if code == split_lines[1]:
                print("This product costs R{}".format(split_lines[3]))
                inventory.close()
    
    def get_quantity():
        inventory = open('inventory.txt','r')
        inventory_list = inventory.readlines()

        code = input("What is the code of the product:")

        for line in inventory_list:
            split_lines = line.split(",")
            if code == split_lines[1]:
                print("There are {} units in inventory".format(split_lines[4]))
                inventory.close()
    
    def __str__(self):
        pass

I haven’t come across the str so I really am not sure how it works, and how to use it. Any advice would be greatly appreciated.

>Solution :

Here is an example:

def __str__(self):
    return f'{self.self.country},{self.self.code},{self.self.product}, {self.cost},{self.quantity })'

This way, when you assign values to a class, you can print its string representation

print(new_shoe)

More info here
https://www.pythontutorial.net/python-oop/python-str/

Leave a ReplyCancel reply