1

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...

2
  • You can make list of objects or something like that. Commented 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/ Commented Mar 7, 2020 at 19:33

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Yes, indeed i've been overwrititing the name of the instance

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.