[Tutor] generating instance names from a list
Alan Gauld
alan.gauld at blueyonder.co.uk
Tue Oct 28 18:15:31 EST 2003
> I'm trying to do something like this (which doesn't work):
>
> class SomeClass:
> names = ['alpha', 'beta']
If you make that list a dictionary:
names = {'alpha':None,'beta':None}
> def somefunc(self):
> for item in self.names:
> self.item = OtherClass()
Then you can do this:
self.names[item] = OtherClass()
> I've had to resort to this, which seems silly.
>
> def somefunc(self):
> self.alpha = OtherClass()
> self.beta = OtherClass()
Why is that silly? If you have a fixed set of names this
is both clear and unambiguous! (If you must do it from a
loop you can probably do some tricks with setattr and
getattr too, but personally I'd just list the attributes
explicitly!)
Using a list of names is better if you have a dynamic list
- ie new names can be added during the lifetime of an object,
or if you have lots of methods that apply to all attributes.
But for most things explicit naming is better IMHO
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list