setattr in class

Wojtek Walczak gminick at bzt.bzt
Fri Sep 12 11:35:02 EDT 2008


On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), 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

> I guess A class not yet exists in line 4. Is it possible to achive
> adding dynamic attributes without using exec?

Yes, it is:

-------------
class A:
   for i in (1, 2):
      locals()['xxx%d' % (i)] = i

print A.xxx1
print A.xxx2
a = A()
print a.xxx1
print a.xxx2
-------------

And the output is:

-----
1
2
1
2
-----

But I definitely don't consider this one as a good programming
practice.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/



More information about the Python-list mailing list