setattr in class

Fredrik Lundh fredrik at pythonware.com
Fri Sep 12 17:18:06 CEST 2008


Bojan Mihelac wrote:

> Hi all - when trying to set some dynamic attributes in class, for
> example:
> 
> class A:
>     for lang in ['1', '2']:
>         exec('title_%s = lang' % lang) #this work but is ugly
>         # setattr(A, "title_%s" % lang, lang) # this wont work
> 
> setattr(A, "title_1", "x") # this work when outside class
> 
> print A.title_1
> print A.title_2
> 
> I guess A class not yet exists in line 4. Is it possible to achive
> adding dynamic attributes without using exec?

Move the for-in loop out of the class definition:

 >>> class A:
...     pass
...
 >>> for lang in ['1', '2']:
...     setattr(A, "title_%s" % lang, lang)
 >>> a = A()
 >>> a.title_1
'1'

A truly dynamic solution (using __getattr__ and modification on access) 
would probably give you a more "pythonic" solution.

</F>




More information about the Python-list mailing list