在Python中通过引用传递整数 [英] Passing an integer by reference in Python

查看:109
本文介绍了在Python中通过引用传递整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中通过引用传递整数?



我想修改传递给函数的变量的值。我已经读过,Python中的所有东西都是按照价值传递的,但必须有一个简单的技巧。例如,在Java中,您可以传递 Integer , Long 等引用类型。


  1. 如何通过引用将整数传递到函数中?

  2. 什么是最佳做法?


解决方案

它在Python中并不完全适用。 Python将引用传递给对象。你的函数内部有一个对象 - 你可以自由地改变该对象(如果可能的话)。但是,整数是不可变的。一个解决方法是在容器中传递可以被突变的整数:

  def change(x):
x [ 0] = 3

x = [1]
变更(x)
印刷x

这最好是丑陋/笨拙的,但是你不会在Python中做得更好。原因是因为在Python中,赋值( = )接受任何对象是右手边的结果并将其绑定到左手边的任何东西*(或者通过它到适当的函数)。

理解这一点,我们可以看到为什么没有办法改变函数内的不可变对象的值 - 你不能改变它的任何属性,因为它是不可变的,并且你不能只给变量赋一个新的值,因为那样你实际上创建了一个新的对象(与旧对象不同),并给它一个旧的名字对象在本地命名空间中。



通常,解决方法是简单地返回所需的对象:

  def multiply_by_2(x):
return 2 * x

x = 1
x = multiply_by_2(x)






*在上面的第一个示例中, 3 实际上被传递给 x .__ setitem __


How can I pass an integer by reference in Python?

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.

  1. How can I pass an integer into a function by reference?
  2. What are the best practices?

解决方案

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

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)


*In the first example case above, 3 actually gets passed to x.__setitem__.

这篇关于在Python中通过引用传递整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆