Reputation: 61
I'm trying to instantiate multiple objects related to the simple class defined below:
class lancamento():
def __init__ (self,date,description,value):
self.date=date
self.description=description
self.value=value
I'd like to use a for loop, which reads a csv file and sets a value to each of the class properties:
a=lancamento(input_a,input_b,input_c)
I printed the following in order to check the result:
print(a.description)
and, of course, the printed result is the one set in the last loop for iteration...
I'd like to instantiate different objects inside this for loop...
Upvotes: 1
Views: 843
Reputation: 502
Instantiating via a loop as you suggested is correct. Below is a list comprehension that will do this for you and then 'a' will be the container for your instances
results = # "SELECT date, description, value FROM DB ..."
a = [lancamento(r[0], r[1], r[2]) for r in results]
for x in a:
print(x.description)
Upvotes: 1
Reputation: 972
You didn't show your for loop code, but I'm guessing you are overwritting the name of your instance at every iteration. You could e.g. create an empty list just before the loop and append the recently created object to that list.
Upvotes: 1