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

Asked

Viewed 804 times

0

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

"attribute 1", "attribute 2", "attribute 3", ...,"attribute"

each row contains the information of a different object. All objects are of the same class.

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

Same thing with the attributes, I don’t want to do:

 objeto.a1 = xxx

 objeto.a2 = xxx

 .

 .

 .

 objeto.aM= xxx
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

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

When you study all the mechanisms of the language before you start creating programs that are more useful than isolated exercise, you discover that Python has a mechanism called list. He is a vector (array) even a little more flexible. This tip ode data structure serves to put several values under the same variable, so you don’t need to create a multitude of them, you don’t need to know how many need (in some languages the array basic has to know the size just before booting it, Python already has a mechanism that allows it to grow if necessary).

When you use a array or a list, which is similar to an array you must have learned in school, you access each element by an index, it would be that number you are using in the names of the variables, however, it stay isolated and can be used up to a variable within 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 of what you need to do to add to the loop that reads the file would be:

lista.append(Obj())

I put in the Github for future reference.

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

  • I understood the answer to the list, but my second question and more about whether it is possible to create a pointer list for each attribute of my class.

  • Pyhon has no pointers.

Browser other questions tagged

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