简体   繁体   中英

Creating multiple instances(objects) of a class derived from a list of str

If I had a class and a list of names where I was asked to instantiate each name in the list as an object of the class, how would I do it?

class PlaceHolder():
    '''This class represents a place holder for this example'''

    pass

listofnames = ['Michael', 'Jay', 'Derrick']
for next_name in listofnames:
    next_name = PlaceHolder()

This does not work. I was wondering if there was a method to implement this?

The reason it won't work is that you are trying to initialize the class to a list item, which isn't going to do anything. The for loop for next_name in listofnames iterates through the values in listofnames .

Try,

listofnames = ['Michael', 'Jay', 'Derrick']
list_dict   = dict() 
for next_name in listofnames:
    list_dict[next_name] = PlaceHolder()

Where each list item has an assigned placeholder and is placed in the dictionary list_dict . It can be accessed by list_dict[next_name]

You are indeed creating objects. The problem is you always store it in the same variable, so you overwrite it. Maybe you are looking something like this

class PlaceHolder():
    '''This class represents a place holder for this example'''

    pass

listofnames = ['Michael', 'Jay', 'Derrick']
instances = list()
for next_name in listofnames:
    instances.append(PlaceHolder())
print(instances)

Or a more pythonic way would be

instances = [PlaceHolder() for next_name in listofnames]
print(instances)

If you absolutely need to set the variables the way you proposed, you can use the following:

for next_name in listofnames:
    exec("{} = Placeholder()".format(next_name))

I really wouldn't recommend this due to the dangers of using exec . Really, don't do this.

It'd be much better to keep these as keys in a dictionary.

my_objects = {}
for next_name in listofnames:
    my_objects[next_name] = Placeholder()

# And access via
my_objects['Michael'] # Placeholder instance

You can try this :

class PlaceHolder():
    '''This class represents a place holder for this example'''

    pass

listofnames = ['Michael', 'Jay', 'Derrick']

for next_name in listofnames:
    globals()[next_name] = PlaceHolder() #create an instance of class PlaceHolder with name=next_name
    listofnames[listofnames.index(next_name)]=globals()[next_name] #replace the string in list with the class instance

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