Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is it possible to iterate trough a class like this, and then give back all the names and do the same thing with price and amount?

What I have tried:

<pre lang="Python">

class Products:
    def __init__(self):
        self.name = "Apple"
        self.price = 3
        self.amount = 0

        self.name = "Banana"
        self.price = 2
        self.amount= 0


product = Products()



for names in product.name:
    print(names)
Posted
Updated 29-Nov-20 3:22am

1 solution

No. You would need to create two instances of the Products class, or the second triplet of lines will overwrite all the values in the first.
Python
class Product:
    def __init__(self, name, price, amount):
        self.name = name
        self.price = price
        self.amount = amount
        
product_1 =  Product("Apple", 3, 0)
product_2 =  Product("Banana", 2, 0)

ProductList = [product_1, product_2]

for obj in ProductList:
     print(obj.name)     
     print(obj.price)
     print(obj.amount)
 
Share this answer
 
Comments
Member 13554627 29-Nov-20 9:24am    
Alright, thank you very much
OriginalGriff 29-Nov-20 9:54am    
You're welcome!

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