[Tutor] iteration is overwriting the previous set value

bob bgailer at alum.rpi.edu
Thu Oct 20 02:20:04 CEST 2005


At 04:16 PM 10/19/2005, Jonas Melian wrote:
>def _pre_save(self):
>     for field in [self.name, self.native_name]:
>         if not field.istitle():
>             #print field.title()
>             field = field.title()
>
>The change I try to do there (field = field.title()) is not being applied

Yes it is. field (a local variable) is being replaced by field.title(). You 
can confirm that by putting
print field after the assignment.

However I guess you want the change to apply to self.name and self.native_name.

Unfortunately you have a list containing the values of self.name and 
self.native_name. Even if you modified the list elements (which assignment 
to field does not do) self.name and self.native_name would not be affected.

Use getattr and setattr to access and assign the attributes, which you 
specify by name.

def _pre_save(self):
     for fieldname in ['name', 'native_name']:
         setattr(self, fieldname) = getattr(self, fieldname).title()

[snip] 



More information about the Tutor mailing list