Passing a string argument by reference
tjreedy at udel.edu
Sun Aug 3 22:36:03 CEST 2003
"Andrew Chalk" <achalk at XXXmagnacartasoftware.com> wrote in message
news:PPdXa.1338$uI7.1016630372 at newssvr12.news.prodigy.com...
> I am a raw beginner to Python. I just read in "Learning Python" that
> assigning to a string argument inside a function does not change the
> in the caller. I want an assignment in the function to alter the
> string in the caller. Is there any way to do this?
As asked, no. Strings are immutable. Period.
However, with the proper infor passed in, you may be able to rebind a
name or other target to a new (string) object.
> For example
> def SafeAdd(self, Variable, Value):
> if self.form.has_key( Value ):
> Variable = self.form[Value].value
> Called with:
> self.SafeAdd(self.txtCIF, 'txtCIF')
I think you want settattr here.
Help on built-in function setattr:
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is
``x.y = v''.
>>> class C: pass
>>> setattr(c, 'a', 1)
Perhaps you want something like 'setattr(self, Value,
self.form[Value].value)'. The param Variable is useless. Arg
self.txtCIF, for instance, is the object currently bound to the name
'txtCIF' and has no info about what name it was bound to. The string
arg such as 'txtCIF' appears to be all you need in the case.
Terry J. Reedy
More information about the Python-list