简体   繁体   中英

Python: how to automatically create instance object?

I want to create instance objects automatically as I explained in the following:

Class MyClass:
     def __init__(self,x):
           self.x = x

list  = ["A","B"]

I want to create the following but automatically, means to loop through the list and create identical object for each element:

A = MyClass(text)
B = MyClass(text)

eg like the following which doesn't work:

# this doesn't work but explains more what I need
for i in list:
    i = MyClass(text)

Thanks to all of your help!

In general, you can't and shouldn't shove things into your namespace like that. It's better to store those instances in a dict or a list

Class MyClass:
     def __init__(self,x):
           self.x = x

lst  = ["A","B"]  # don't use list as an identifier

myclasses = {k: MyClass(text) for k in lst}

Now your instances are

myclasses['A'] , myclasses['B'] etc.

If you really want to create a handful of variables in your namespace:

A, B = (MyClass(text) for x in range(2))

note that this means you need to be explicit. You can't get the A,B from a file or user input etc.

Don't be tempted to use exec to pull this off. It's probably the wrong way to go about solving your problem. Tell us why you think you need to do it instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM