0

Is there any way to auto create objects in python

class A:
   pass
a = A()

I would like to automatically create objects for a class. I need to parse a bunch of xml and I'd like to create an object for one file (entry parse). Or I need to create some random names?

glls
  • 2,325
  • 1
  • 22
  • 39
luck.duck
  • 3
  • 2
  • 1
    looks like a duplicate of http://stackoverflow.com/questions/3451779/how-to-dynamically-create-an-instance-of-a-class-in-python – Vikas Madhusudana May 25 '16 at 07:20
  • It's not clear from your description where you are running into trouble. You have already written code that automatically creates an instance `a` of your class `A`. If you need many instances of this class, you could store them in a list, e.g., `files=['file1.xml', 'file2.xml']; parsers=[A(f) for f in files]`. But other options are possible, depending on your problem... – Matthias Fripp May 25 '16 at 07:32

1 Answers1

1

You don't have to manually assign variable names to the object instances, simply store them in a list when you create them dynamically, like in this example where a list of objects gets created with information from a file:

class A:
    def __init__(self, words):
        self.words = words

a_objects = []
file = open("testfile.txt")
for line in file:
    words = line.split()
    a_objects.append(A(words))

If you need to access the objects directly using a key, you will have to use a dictionary instead of a list:

a_objects = {}

You can add key-value pairs to it like this:

words = line.split()
key = words[0]
a_objects[key] = A(words)
Byte Commander
  • 6,506
  • 6
  • 44
  • 71
  • There is `)` missing in `a_objects.append(A(words)` – abukaj May 25 '16 at 07:38
  • @abukaj Oops, you're right, of course. Thanks for pointing it out, I fixed it. – Byte Commander May 25 '16 at 07:39
  • thanks a lot! because I'm little frustrating about that how create object not only manualy assign them to some variable( – luck.duck May 25 '16 at 07:44
  • @luck.duck I did not really understand what you wanted to tell me with that comment... Did this answer solve your question? In that case please accept it by clicking the grey tick button on its left. Otherwise please explain what you need to be different. Thanks and welcome to Stack Overflow. - Did you take the [tour] already btw? – Byte Commander May 25 '16 at 07:54