Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading