Instantiating multiple objects

Asked

Viewed 61 times

0

I’m trying to instantiate an object multiple times, from a single class, defined below:

class lancamento():

def __init__ (self,date,description,value):

    self.date=date
    self.description=description
    self.value=value

I would like to use a loop for, which reads a csv file and assigns a value to each of the class properties:

a=lancamento(input_a,input_b,input_c)

I printei to test the result:

print(a.description)

and clearly printed the value of the last assignment of the loop for.

I would like to find a way that I can differentiate each of the instantiated objects...

1 answer

0

It is possible to work with a list, so for each CSV row you instance the class lancamento.

I create a variable to contain class instances lancamento, Initiating it as an empty list:

lancamentos = []

I then read the CSV file:

with open("csv.csv", "r") as csv:
  for line in csv:
    data = line.strip().split(";")

Now the variable data contains the CSV data, so I just instantiate the class lancamento and put its value inside the list lancamentos:

lancamentos.append( lancamento(data[0], data[1], data[2]) )

The complete code would look like this:

class lancamento():
  def __init__ (self, date, description, value):
    self.date = date
    self.description = description
    self.value = value

lancamentos = []

with open("csv.csv", "r") as csv:
  for line in csv:
    data = line.strip().split(";")
    lancamentos.append( lancamento(data[0], data[1], data[2]) )

for lanc in lancamentos:
  print(lanc.description)

See that I made a for on the list lancamentos to display the values that were returned from CSV.


See this online example: https://repl.it/repls/QuaintLawfulWireframe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.