函数内部变量的赋值改变了外部的赋值 - Python [英] Assignment of variables inside function changes assignment outside - Python

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

问题描述

我从使用 Matlab 转向使用 Python,使用函数时的变量赋值让我感到困惑.

我有一个代码如下:

a = [1,1,1]def保持(x):y = x[:]y[1] = 2返回 y定义更改(x):y = xy[1] = 2返回 yaout = 保持(a)打印(a,aout)aout = 变化(一)打印(a,aout)

第一个打印语句给出[1, 1, 1] [1, 2, 1],而

第二个给出[1, 2, 1] [1, 2, 1].

我了解到(来自 Matlab)对函数内变量的操作是局部的.但是在这里,如果我不在函数内部复制变量,那么函数外部的值也会发生变化.这几乎就像变量被定义为global.

如果有人能解释变量在这两种方法中如何以不同方式分配,以及如果想要将变量发送到函数而不影响函数外部的值,最佳实践是什么,这将非常有帮助?谢谢.

解决方案

参数传递是通过赋值完成的.在changes中,隐含发生的第一件事是
x = a 当您调用 changes(a) 时.由于assingment 永远不会复制数据,您会改变a.

keeps 中,您不会改变参数列表,因为 x[:] 正在创建一个(浅)副本,然后名称 y分配给.

我强烈建议您观看 关于 Python 名称和值的事实和神话.>

I moved from using Matlab to Python and the variable assignment while using functions is confusing me.

I have a code as follows:

a = [1,1,1]

def keeps(x):
    y = x[:]
    y[1] = 2
    return y

def changes(x):
    y = x
    y[1] = 2
    return y

aout = keeps(a)
print(a, aout)

aout = changes(a)
print(a, aout)

The first print statement gives [1, 1, 1] [1, 2, 1], while

the second one gives [1, 2, 1] [1, 2, 1].

I had a understanding (coming from Matlab) that the operations on a variable within a function are local. But here, if I don't make a copy of the variable inside a function, the values change outside the function as well. It's almost as if the variable is defined as global.

It will be very helpful if someone can explain how the variables are allocated differently in both the methods and what are the best practices if one wants to send a variable to the function without affecting it's value outside the function? Thanks.

解决方案

Argument passing is done by assignment. In changes, the first thing that happens implicitly is
x = a when you call changes(a). Since assingment NEVER copies data you mutate a.

In keeps you are not mutating the argument list because x[:] is creating a (shallow) copy which then the name y is assigned to.

I highly recommend watching Facts and Myths about Python names and values.

这篇关于函数内部变量的赋值改变了外部的赋值 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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