0

My goal is, given an Excel or CSV file, to automatically create instances of one object. After some research, I saw that similar questions have been asked. But in most of the cases, the author only wanted to put instances into a list to print information on them (like: Python creating class instances in a loop).

What I need, is not only to create separate instances of a class, but also to be able to call on these distinct instances later in the code. Also, the main point of this, is that my file is dynamic. The one I put just below is just a toy example, my goal being to be able to automatically process bigger and more complex "models".

Let's have an example. Given the following file:

Example of File

I would like to create different instances of the following object to store the information given in the file:

class Element
    name = ""
    Property1 = []
    Property2 = []

    def add_name(self, name):
        self.name = name

    def add_pos_reg(self, p1):
        self.Property1.append(p1)

    def add_neg_reg(self, p2):
        self.Property2.append(p2)

I thought of using the classic way of instancing an object in a loop, and then stocking the instances in a list:

    ListeElement = []
    for i in range(2, max_row):
       e=Element("get the property from the file") ## I already have a custom function to get the properties from the file into the instance. ##
       ListeElement.append(e)

But then, I think that this way does not create distinct instances, and also I am not even sure that I will be able to call on specific instances stocked in the list later in my code.

I am sorry if this is a redundant question, I usually find what I want to do using the search function on this website, but I am getting stuck there.

Community
  • 1
  • 1
Alors
  • 1
  • 1
  • What makes you think you can't access them in the list? You can get them with `ListeElement[index]` a dict would make accessing by name even easier – Maarten Fabré Mar 23 '17 at 19:44
  • How would I call them ? I don't know to which number of the index each instance is assigned. Moreover, for my purposes, I will need to call the instance by refering to its attribute "name", and I have no idea how to get that out of a list. – Alors Mar 23 '17 at 23:55
  • Which is where the dict comes in. You can fill it with (name, Element) pairs – Maarten Fabré Mar 24 '17 at 06:42

0 Answers0