[Tutor] iteration is overwriting the previous set value
bgailer at alum.rpi.edu
Thu Oct 20 16:49:22 CEST 2005
At 12:32 AM 10/20/2005, Jonas Melian 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]
>SyntaxError: can't assign to function call
Oops me bad. Did not test! setattr(self, fieldname, getattr(self,
>Danny Yoo's goes ok
>You've the reason: there is no benefit in using "if not field.istitle():"
Is that a question or an appreciation? If question:
It takes execution time to test to see if something is already set. If the
variables are already set the cost of checking them to avoid assigning then
is about the same as the cost of just assigning. If the variables are not
set then the cost of checking and assigning is twice the cost of just
assigning. Also just assigning is less code to write and maintain.
More information about the Tutor