[Tutor] generating instance names from a list

Thomi Richards thomi at imail.net.nz
Mon Oct 27 23:43:10 EST 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>
> I'm trying to do something like this (which doesn't work):
>
> class SomeClass:
>   names = ['alpha', 'beta']
>
>   def somefunc(self):
>       for item in self.names:
>           self.item = OtherClass()
>
> class OtherClass:
>    ....
>

Hi!

I tried this a wee while ago, so I may as well share my results with you.

The only way you can do this (AFAIK) is like so:

names = ['alpha','beta']

for name in names:
	exec('%s = someClass()' % (name))

However, I found out very quickly that this really isn't a good idea... you 
might want to try doing something like:

1.- storing your class instance in a list?:

names = ['alpha','beta']
objects = []

for name in names:
	objects.append(someClass(name))

inside the someClass class it could assign the value passed to it to an 
internal attribute....

2.- another (better?) way is to store your class instances in a dictionary, 
like so:

names = ['alpha','beta']
objects = {}

for name in objects:
	objects[name] = someClass()

now, you can use this dictionary like so:

objects['alpha'].somemethod()

all the above is untested code, but here's a short snippet to illustrate what 
I'm getting at:

>>> def foo():
...     print "hi"
... 
>>> d['foo'] = foo
>>> d['foo']
<function foo at 0x40210f0c>
>>> d['foo']()
hi


simple eh?

HTH!


- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/nfPh2tSuYV7JfuERAo19AJ4+sBShWDWpnU4fi0dC54+GSg4ciwCdGCsx
q8/Ko9vNFxq1MDfQSo2hyqA=
=VAdb
-----END PGP SIGNATURE-----




More information about the Tutor mailing list