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...
-
You can make list of objects or something like that.Boseong Choi– Boseong Choi2020年03月05日 12:08:02 +00:00Commented Mar 5, 2020 at 12:08
-
Please don't forget to upvote all working answers, and accept the one you like the most. Probably you know this, but this is to let the community know which answers were useful and to reward the people for their time and effort as well ;) See this meta.stackexchange.com/questions/5234/ and meta.stackexchange.com/questions/173399/alan.elkin– alan.elkin2020年03月07日 19:33:42 +00:00Commented Mar 7, 2020 at 19:33
2 Answers 2
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)
Comments
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.