setattr in class

Bojan Mihelac bmihelac at gmail.com
Fri Sep 12 11:08:18 EDT 2008


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



More information about the Python-list mailing list