[Tutor] Dynamically named objects
Marc Tompkins
marc.tompkins at gmail.com
Fri Dec 28 09:15:34 CET 2007
Sorry, meant to respond to the list, not just the OP...
---------- Forwarded message ----------
From: Marc Tompkins <marc.tompkins at gmail.com>
Date: Dec 28, 2007 12:13 AM
Subject: Re: [Tutor] Dynamically named objects
To: Michael Bernhard Arp Sørensen <michaelarpsorensen at stevnstrup.dk>
I don't think there's any need for eval - I'll leave the sermon about why
eval is a Bad Thing for someone else - and if your objects are going to
spend most of their "lives" in a list or dictionary, they don't really need
meaningful individual names. (I mean, instead of naming each one class1,
class2, etc. you can simply refer to them as classDict[1], classDict[2],
etc. or classList[1], etc.)
How's this:
#====================================
class thingy():
example = "Just testing - "
def __init__(self, num):
self.example = self.example + str(num)
thang = {}
for x in range(1,4):
thang[x] = thingy(x)
for item, value in thang.iteritems():
print item, value.example
#=====================================
On Dec 27, 2007 11:44 PM, Michael Bernhard Arp Sørensen <
michaelarpsorensen at stevnstrup.dk> wrote:
> Hi there.
>
> I need to instantiate objects on the fly and put the in a list/dict for
> later use. I was thinking of this:
>
> objectlist = []
> newobjectname = "object1"
> classname = "class1" + "()"
> objectlist.append(newobjectname = eval(classname) )
> objectlist[0].method("hello world")
>
> Can this be done? If not, is there a work around or some design pattern
> for this situation?
>
> --
> Venlig hilsen/Kind regards
>
> Michael B. Arp Sørensen
> Programmør / BOFH
>
> I am /root and if you see me laughing you better have a backup.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
www.fsrtechnologies.com
--
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071228/dae25ac6/attachment.htm
More information about the Tutor
mailing list