[Tutor] generating instance names from a list
Karl Fast
karl.fast at pobox.com
Tue Oct 28 12:25:58 EST 2003
This works. This is the solution I was looking for. Much thanks.
I've summarized the problem and the solution below, for anyone who
cares and doesn't want to piece together the thread.
> When the name of an attribute is in a variable, you can use the
> builtin functions:
> getattr(obj, name[,default])
> hasattr(obj, name)
> setattr(obj, name, value)
> to work with the attribue and its object.
THE PROBLEM:
You've got a list of names and want to create an instance for each
item in the list.
THE SOLUTION:
class SomeClass:
def somefunc(self):
names = ['alpha', 'beta']
for item in names:
setattr(self, item, OtherClass())
class OtherClass:
....
So if you do this:
>>> a = SomeClass()
>>> a.somefunc()
You will now have a.alpha and a.beta, both instances of OtherClass.
--karl
More information about the Tutor
mailing list