1

I am writing a simple Checkout program in python My checkout class is

 Class Checkoutregister


 product1 = Product(510, 'milk', 6)
 product2 = Product(511, 'coke', 3)
 product3 = Product(512, 'chicken', 10)
 product4 = Product(513, 'shirt', 40)
 product5 = Product(514, 'kitkat', 4)
 list=[]

This is my product class

class Product:
def __init__(self,barcode,name,price):
    self.barcode=barcode
    self.name=name
    self.price=price

I am writing a function to insert the products to the list and print the list..but I am getting problem while printing the list

 def insertProduct():
        Checkoutregister.list.insert(0,Checkoutregister.product1)
        print Checkoutregister.list

The print statement prints like

[<Product.Product instance at 0x04AEB6C0>]

how can I print the list and how can I iterate around the list to print all the inserted products in the list when I add all the products in the list

1 Answer 1

2

You need to add the _str_ method to your product class

Try:

class Product:
  def __init__(self,barcode,name,price):
    self.barcode=barcode
    self.name=name
    self.price=price
  def __str__(self):
        return "ProdName: "+self.name+" Barcode: "+str(self.barcode)+" Price: $"+str(self.price)

product1 = Product(510, 'milk', 6)

print(product1)

This will print Product objects like:

ProdName: milk Barcode: 510 Price: $6

If you want to have a list[] of Product objects that you then want to iterate through and print each one, that would look like the following:

# create our products
product1 = Product(510, 'milk', 6)
product2 = Product(420, 'hotdog buns', 3)
# create a list to hold our products
list_of_prods = []
# add our products to the list[]
list_of_prods.append(product1)
list_of_prods.append(product2)
# iterate over our list[] with a simple for:each loop
for prod in list_of_prods:
  print(prod)

This would print out all of the Product's in list_of_prods[]. Output looks like:

ProdName: milk Barcode: 510 Price: $6
ProdName: hotdog buns Barcode: 420 Price: $3

From your original question, it looks like you were trying to accomplish this by creating a Checkoutregister class - the idea there would be the same, and your insertProduct() method would just need to add products to the Checkoutregister.list.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. But i want to store a number of products in an array and display them later.how can i do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.