Create object name from string value?

Ben Finney ben+python at benfinney.id.au
Wed Jan 20 22:31:11 EST 2010


Gnarlodious <gnarlodious at gmail.com> writes:

> I want to declare several objects from names in a list:
>
> objects=['object1', 'object2', 'object3', 'object4']
> for objectName in objects:
> 	objectName=classname()

Since (I presume) you are a newcomer to Python, it's best to learn the
common style <URL:http://www.python.org/dev/peps/pep-0008/>. I will
assume the above is written as::

    object_names = ['object1', 'object2', 'object3', 'object4']
    for object_name in object_names:
        object_name = Class()

> That fails

Well, it succeeds (runs successfully). But I get what you mean: it fails
to do what you expected.

> So how to make an object whose name is the value in the variable?

This is almost certainly better done with a dictionary. Like so::

    object_names = ['object1', 'object2', 'object3', 'object4']
    objects = {}
    for object_name in object_names:
        objects[object_name] = Class()

There are shortcuts that can be used to create the dictionary without
the separate list of names. But for now the above should make sense
immediately and help you get to the meat of the problem.

-- 
 \         “We now have access to so much information that we can find |
  `\  support for any prejudice or opinion.” —David Suzuki, 2008-06-27 |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list