[Tutor] generating instance names from a list

Lloyd Kvam pythontutor at venix.com
Tue Oct 28 11:56:34 EST 2003


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.

def somefunc(self):
     for item in self.names:
         setattr(self, item, OtherClass())

should do what you intended.

Karl Fast wrote:

> I've got a list and want to create an instance for each item in the
> list based on the list value. In other words, I want to create a set
> of objects based on some list values.
> 
> 
> 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:
>    ....
> 
> 
> Obviously that's not going to work. It creates self.item and keeps
> reassigning it until the list is exhausted. 
> 

> 
> --karl
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list