PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to use __str__ function to return a string representation of a class

 November 14, 2022     class, external, python, txt     No comments   

Issue

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/



Answered By - ssanga
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing