[Tutor] iteration is overwriting the previous set value
Jonas Melian
jonasmg at SoftHome.net
Thu Oct 20 09:39:08 CEST 2005
Your code is correct. Thanks
I understood it. 'field' is a local variable inner that loop.
Respect to a related matter, a should be '42'
Danny Yoo wrote:
>On Thu, 20 Oct 2005, Jonas Melian wrote:
>
>
>
>Hi Jonas,
>
>
>Do you understand why it isn't working?
>
>The issue is that 'field' is just another variable name, and the
>assignment just redirects that particular name to some other value. So
>when we're doing:
>
> field = field.title()
>
>this statement has no effect on any other name, and in particular, doesn't
>do any mutation on 'self'.
>
>
>As a related matter:
>
>######
>
>
>>>>a = "42"
>>>>b = a
>>>>b = "17"
>>>>
>>>>
>######
>
>What do you expect 'a' to be?
>
>
>
>
>
>>I'm supposed that each iteration is overwriting the previous set value
>>
>>how solve it? using a dict?
>>
>>
>
>One way to do this is to use getattr() and setattr() so that we can do
>mutation on 'self'. Your example above should work with:
>
>###################################################
>def _pre_save(self):
> for fieldname in ['name', 'native_name']:
> value = getattr(self, fieldname)
> if not value.istitle():
> setattr(self, fieldname, value.title())
>###################################################
>
>
>Hope this helps!
>
>
>
>
More information about the Tutor
mailing list