简体   繁体   中英

Python string to object (or class?)

I am trying to loop through a list of known elements so I can check if they were submitted properly, then do something with them. Problem is, my elements are strings, but the corresponding element object is needed to assign a value to a user object.

Should something else be where eval(element) is?

elements = ('first_name', 'last_name', 'email')

u = request.user

for element in elements:    
    if not element in form.errors:
        dajax.alert('alert: %s' % form.cleaned_data[element])
        u.eval(element) = form.cleaned_data[element]
        dajax.add_css_class('div #%s' % element , 'form-group has-success')

像这样使用setattr

setattr(u, element, form.cleaned_data[element])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM