[Tutor] iteration is overwriting the previous set value

Jonas Melian jonasmg at SoftHome.net
Thu Oct 20 09:32:48 CEST 2005


bob wrote:

> 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]
>
This fails:
SyntaxError: can't assign to function call

Danny Yoo's goes ok

You've the reason: there is no benefit in using "if not field.istitle():"

Thanks all



More information about the Tutor mailing list