setattr in class

Michael Palmer m_palmer45 at yahoo.ca
Fri Sep 12 18:53:00 EDT 2008


On Sep 12, 11:08 am, Bojan Mihelac <bmihe... at gmail.com> 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?
>
> thanks,
> Bojan

Is it really worth it? If the names of the attributes are only known
at runtime, why not just use a dict - that's what they are for. If you
want a dict plus some special behaviour, just write a class that
inherits from dict, or use UserDict.DictMixin.



More information about the Python-list mailing list