Click here to Skip to main content
15,171,851 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I keep getting the following error in my coding

print("Product", products.product_name)
AttributeError: 'str' object has no attribute 'product_name'


This is not the complete coding as there is multiple files but the display method is causing an error and is not able to return the product name, I am trying to get the display method to return the name of the product "Toy" I have included the product class and the code which contains the attributes, can anyone advise I feel like I have looked at this all day with no avail (apologies beginner student).


Python
#Creating shopping cart class
class Shopping_Cart:

    def __init__(self, cart_id):
        self.cart_id = cart_id
        self.products=[]

    # Method Display:
    def display(self):
        print("Shopping Cart ID", self.cart_id)
        for products in self.products:
            print("Product", products.product_name)


class Products:
def __init__(self, product_name, product_id, product_price, quantity, supplier):
  self.product_name = product_name
  self.product_id = product_id
  self.product_price = product_price
  self.supplier = supplier
  self.quantity = quantity


product_1 = Products("Top", 1, 15, 100, "3'rd party")
clothes_store.add_new_product(product_1)


What I have tried:

I have tried the above code numerous times , tried not using string which I thought was causing the issues
Posted
Updated 5-Oct-21 7:51am

1 solution

The issue is that you are using the same variable name for the item returned from the products list.
Python
for products in self.products:
    print("Product", products.product_name)

So you now have a local variable called products which is the first item in your products list. Assuming it is a string it does not have an attribute named product_name. Your code is somewhat confusing as it is not clear what items you have in the list.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900