|
Posted by Bryan Olson on 09/30/07 19:36
Summercool wrote:
> I wonder which language allows you to change an argument's value?
> like:
>
> foo(&a) {
> a = 3
> }
>
> n = 1
> print n
>
> foo(n) # passing in n, not &n
> print n
>
> and now n will be 3. I think C++ and PHP can let you do that, using
> their reference (alias) mechanism. And C, Python, and Ruby probably
> won't let you do that. What about Java and Perl?
I think you've missed how Python works, and probably others.
A Python function receives a reference to the argument, and
can modify the object if the object is mutable.
Nevertheless, assigning to the parameter's name will not
change the passed object. This function does nothing:
def clear_list_wrong(lst):
lst = [] # useless re-binding of local name
This version empties the passed list:
def clear_list(lst):
del lst[:]
> is there any way to prevent a function from changing the argument's
> value?
Sure. First choice: Don't change the value in the function.
Alternatives include making a copy to use as the argument.
> isn't "what i pass in, the function can modify it" not a desireable
> behavior if i am NOT passing in the address of my argument? For one
> thing, if we use a module, and call some functions in that module, and
> the module's author made some changes to his code, then we have no way
> of knowing what we pass in could get changed.
Don't rely on undocumented behavior. Modules worth using are by
good programmers. Authors of library modules tend to be zealous
about not breaking client code.
--
--Bryan
Navigation:
[Reply to this message]
|