On Thu, 20 Oct 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 I changed code so that you do 'self.foo = bar' statements for
> each attribute instead of using a loop and see if data gets saved, and
> it goes ok
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!
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor