How to create a list of objects of variable size, and assign their attributes without listing them one by one?

0

I need to read a file and pass its information to a list of objects. The file is in the format:

"attribute1", "attribute2", "attribute3", ..., "attributeN"

Each line contains the information for a different object. All objects are of the same class.

How do I create an object to associate its values if I do not know how many lines the file can have? I do not want to have to declare N objects, how can I do iteratively?

The same thing with the attributes, I do not want to do:

 objeto.a1 = xxx

 objeto.a2 = xxx

 .

 .

 .

 objeto.aM= xxx
    
asked by anonymous 28.11.2018 / 15:47

1 answer

0

This seems to be the same problem covered in How to assign elements of a list to different variables in Python? .

When you study all the mechanisms of the language before you start to create programs that are more useful than isolated exercise I discovered that Python has a mechanism called list. It is a vector ( array ) up to a little more flexible. This type of data structure serves to put several values under the same variable, so you do not have to create a myriad of them, you do not need to know how many you need (in some languages the basic array of initializing it, Pyhton already has a mechanism that allows it to grow if necessary).

When you use an array or a list, which looks like an array that you must have learned in school, you access each element by an index, that number you are using in variable names , but it stays isolated and can be used up to a variable inside it, which gives a lot of flexibility.

I'll use the name you used, but it would be better to use more meaningful names:

objeto.a[1]
objeto.a[2]
.
.
.
objeto.a[N]

An approximate code you need to add to the loop that reads the file would be:

lista.append(Obj())

Being Obj would be this class that created an object by reading a file data.

    
28.11.2018 / 16:10