[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Dynamically created objects

Michael Bernhard Arp Sørensen

12/28/2007 7:15:00 AM

Hi there.

I need to create objects on the fly in my program. The names of the
objects must be unique, obviously, and I need to put them in a list for
later use.

How do i set the name of an object if the name is stored in another
variable?

I've looked in the O'Reiley Python Cookbook and on google, but no joy.

Thanks in advance.

/Tram
2 Answers

Gabriel Genellina

12/28/2007 7:40:00 AM

0

En Fri, 28 Dec 2007 04:14:43 -0300, Michael Bernhard Arp Sørensen
<murderbystealth@gmail.com> escribió:

> I need to create objects on the fly in my program. The names of the
> objects must be unique, obviously, and I need to put them in a list for
> later use.
>
> How do i set the name of an object if the name is stored in another
> variable?
>
> I've looked in the O'Reiley Python Cookbook and on google, but no joy.

Use a dictionary as a container.

py> ns = {}
py> name = "Joe"
py> o = object()
py> ns[name] = o
py> another = set("another")
py> ns["another"] = another
py> ns
{'Joe': <object object at 0x009D0478>,
'another': set(['a', 'e', 'h', 'o', 'n', 'r', 't'])}

--
Gabriel Genellina

Steven D'Aprano

12/28/2007 7:44:00 AM

0

On Fri, 28 Dec 2007 08:14:43 +0100, Michael Bernhard Arp Sørensen wrote:

> Hi there.
>
> I need to create objects on the fly in my program. The names of the
> objects must be unique, obviously, and I need to put them in a list for
> later use.

Why do you think they need names? If you have them in a list, just refer
to them by the list and index. Or a dict and a key.

E.g. instead of this:


# this doesn't work
for i in range(10):
"foo" + i = "some data here" # variables like foo0, foo1 ...
process(foo0, foo1, foo2)



do this:

foo = []
for i in range(10):
foo.append("some data here")
process(foo[0], foo[1], foo[2])




> How do i set the name of an object if the name is stored in another
> variable?


If you really need to do this, and I doubt that you do, here's one way:


>>> bird
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bird' is not defined
>>> globals()["bird"] = "a parrot with beautiful plumage"
>>> bird
'a parrot with beautiful plumage'


If you're tempted to try the same trick with locals(), don't bother -- it
won't reliably work.

If you are absolutely sure that the data is safe (i.e. you control it,
not random users via a web form) you can also use exec.



--
Steven