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?

2
  • 1
    looks like a duplicate of stackoverflow.com/questions/3451779/… Commented May 25, 2016 at 7: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... Commented May 25, 2016 at 7:32

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

There is ) missing in a_objects.append(A(words)
@abukaj Oops, you're right, of course. Thanks for pointing it out, I fixed it.
thanks a lot! because I'm little frustrating about that how create object not only manualy assign them to some variable(
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.