Python:保留对在函数内进行的变量的更改 [英] Python: Keep changes on a variable made within a function

查看:54
本文介绍了Python:保留对在函数内进行的变量的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python中一个相当简单的任务有疑问,但是,我没有找到解决方案.我想给python中一个已经存在的变量分配一个新值.但是,我对函数中的变量所做的更改不会保留在变量中.

I have a question on a fairly simple task in python, however, I didn't manage to find a solution. I would like to assign a new value to an already existing variable in python. However, the changes I am doing to the variable within the function don't stick to the variable.

这是我的问题的简化示例:

Here is a simplified example of my problem:

y = 1
x = None

def test(var):

    var = y

    return var 


test(x)
print(x)

打印仅返回任何内容.因此,我对函数中的变量所做的更改是永久性的.

The print simply returns none. So the changes I have done to the variable within the function are non permanent.

如何使对输入变量的更改永久生效?

How can I make the changes on the input-variable of the function permanent?

提前谢谢!

推荐答案

这是通过值将变量传递给函数的示例.默认情况下,当您将变量传递给Python中的函数时,它会按值传递.

This is an example of passing variables to functions by value. By default, when you pass a variable to a function in Python, it is passed by value.

这意味着,将使用具有相同 x 值的新作用域创建一个新变量.因此,新的 x 发生的任何更改都不会反映到函数范围之外的 x .

What it means is, that a new variable with a new scope is created with the same value of x. So, any change that happens to the new x is not reflected to the x outside the function's scope.

如果您想从函数中获取值,则可以使用return语句(如前所述). return 从函数返回值.但是,在您的示例中,没有变量可以接收它.因此,它丢失了.

If you want to get the value from the function back, you can use the return statement (as you have used). return returns the value back from the function. However, in your example there is no variable to receive it. Hence, it is lost.

您必须将函数调用为 x = test(x).这样可以确保 x 从函数接收回该值.

You would have to call the function as x = test(x). This ensures that x receives the value back from the function.

这篇关于Python:保留对在函数内进行的变量的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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