Modify parameter as a side

Possible Duplicate:
Python: How do I pass a variable by reference?

I'm trying to write a function that modifies one of the passed parameters. Here's the current code:

def improve_guess(guess, num): 
  return (guess + (num/guess)) / 2

x = 4.0
guess = 2.0
guess = improve_guess(guess, x)

However, I want to write the code in such a way that I don't have to do the final assignment. That way, I can just call:

improve_guess(guess,x) 

and get the new value in guess.

(I intentionally didn't mention passing-by-reference because during my net-searching, I found a lot of academic discussion about the topic but no clean way of doing this. I don't really want to use globals or encapsulation in a list for this.)


You can't do this directly since integer and floating-point types are immutable in Python.

You could wrap guess into a mutable structure of some sort (eg a list or a custom class), but that would get very ugly very quickly.

PS I personally really like the explicit nature of guess = improve_guess(guess, x) since it leaves no doubt as to what exactly is being modified. I don't even need to know anything about improve_guess() to figure that out.


But those are the only two ways to do it: either use a global, or use a mutable type like a list. You can't modify a non-mutable variable in Python: doing so just rebinds the local name to a new value.

If you really don't like wrapping in a list, you could create your own class and pass around an instance that will be mutable, but I can't see any benefit in doing that.

链接地址: http://www.djcxy.com/p/20834.html

上一篇: python如何在赋值运算符后赋值

下一篇: 修改参数作为一面