在 Python 中通过引用传递整数 [英] Passing an integer by reference in Python
问题描述
如何在 Python 中通过引用传递整数?
How can I pass an integer by reference in Python?
我想修改传递给函数的变量的值.我读过 Python 中的所有内容都是按值传递的,但必须有一个简单的技巧.例如,在 Java 中,您可以传递 Integer
、Long
等的引用类型.
I want to modify the value of a variable that I am passing to the function. I have read that everything in Python is pass by value, but there has to be an easy trick. For example, in Java you could pass the reference types of Integer
, Long
, etc.
- 如何通过引用将整数传递给函数?
- 最佳做法是什么?
推荐答案
它在 Python 中不太适用.Python 传递对对象的引用.在您的函数中,您有一个对象——您可以随意修改该对象(如果可能).然而,整数是不可变的.一种解决方法是将整数传递到可以变异的容器中:
It doesn't quite work that way in Python. Python passes references to objects. Inside your function you have an object -- You're free to mutate that object (if possible). However, integers are immutable. One workaround is to pass the integer in a container which can be mutated:
def change(x):
x[0] = 3
x = [1]
change(x)
print x
这充其量是丑陋/笨拙的,但你不会在 Python 中做得更好.原因是因为在 Python 中,赋值 (=
) 将任何对象作为右侧的结果并将其绑定到左侧的任何对象 *(或将其传递给适当的函数).
This is ugly/clumsy at best, but you're not going to do any better in Python. The reason is because in Python, assignment (=
) takes whatever object is the result of the right hand side and binds it to whatever is on the left hand side *(or passes it to the appropriate function).
理解了这一点,我们就可以明白为什么没有办法改变函数内不可变对象的值——你不能改变它的任何属性,因为它是不可变的,你不能只分配变量"" 一个新值,因为这样您实际上是在创建一个新对象(与旧对象不同)并为其赋予旧对象在本地命名空间中的名称.
Understanding this, we can see why there is no way to change the value of an immutable object inside a function -- you can't change any of its attributes because it's immutable, and you can't just assign the "variable" a new value because then you're actually creating a new object (which is distinct from the old one) and giving it the name that the old object had in the local namespace.
通常的解决方法是简单地返回您想要的对象:
Usually the workaround is to simply return the object that you want:
def multiply_by_2(x):
return 2*x
x = 1
x = multiply_by_2(x)
<小时>
*在上面的第一个例子中,3
实际上被传递给了 x.__setitem__
.
*In the first example case above, 3
actually gets passed to x.__setitem__
.
这篇关于在 Python 中通过引用传递整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!