Python函数不应更改全局变量 [英] Python function not supposed to change a global variable

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

问题描述

我对Python和Numpy相当陌生,在将MATLAB程序转换为Python时遇到了这个问题.

I am fairly new to Python and Numpy, and I encountered this issue when translating a MATLAB program into Python.

据我所知,以下代码通过修改全局变量(即使不应该这样做)也表现异常.

As far as I can tell, the code below is behaving abnormally by modifying a global variable even though it shouldn't.

import numpy as np

A = np.matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

def function(B):
    B[1,1] = B[1,1] / 2
    return B

C = function(A)

print(A)

输出为:

[[0 1 2]
 [3 2 5]
 [6 7 8]]

该函数将矩阵的中间数除以二并返回.但似乎它也在改变全局变量.

The function divides the middle number of the matrix by two and returns it. But it seems it is also altering the global variable.

在这里,这个问题很容易避免,但是我试图理解为什么会出现.

Here, the issue can easily be avoided but I am trying to understand why it arises.

由于某些原因,如果函数将WHOLE矩阵除以2,则不会发生这种情况.

For some reasons, this does NOT happen if the function divides the WHOLE matrix by 2.

import numpy as np

A = np.matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

def function(B):
    B = B / 2
    return B

C = function(A)

print(A)

输出为:

[[0 1 2]
 [3 4 5]
 [6 7 8]]

推荐答案

在第一种情况下

def function(B):
    B[1,1] = B[1,1] / 2
    return B

您可以更改名称为B指向的可变对象的特定元素的内容.如上一个答案中所述.

you alter the content of a specific element of the mutable object pointed to by the name B. As described in the previous answer already.

在,

def function(B):
    B = B / 2
    return B

关键是B / 2完全是一个新对象.输入的对象不变.

the point is that B / 2 is a new object altogether. The object given as input is not altered.

将其重新分配给本地名称B的事实并不重要.它使B不再指向作为函数输入提供的原始对象,而是指向一个全新的对象实例.函数返回.

The fact that you reassign it to the local name B is unimportant. It makes B no longer point to the orginal object provided as input to the function, but to a completely new object instance. That the function returns.

因此,正确地,名称A所指向的对象实例即使是可变的也不受影响.

So, correctly, the object instance pointed to by the name A is unaffected, even if mutable.

这篇关于Python函数不应更改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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