I define and use a 2 dimensional numpy array in the program main function. A function called within main then tries to modify the numpy array without success. The array is declared as global in the second function but I still get the following error:
必须在main函数中将其声明为global。否则,您只是在创建一个局部变量,而不是全局变量。无论是否使用global,都不能访问另一个函数的局部变量;只能访问全局变量。在I thought that you could read a variable from main within a function without calling it global but that if you modified it within the function you had to declare it global in the function.
很接近真实……但是创建它就等于修改了它。在
所以,与其这样:def sub():
global name_of_array
return name_of_array[0, 0]
def main():
name_of_array = np.zeros((2, 2))
sub()
…这样做:
^{pr2}$
不过,还有一个更好的解决方案:只需将数组作为参数传递,而不是使用全局:def sub(name_of_array):
return name_of_array[0, 0]
def main():
name_of_array = np.zeros((2, 2))
sub(name_of_array)
如果你避免了因为你来自C++之类的语言,担心这会浪费大量的时间和内存拷贝整个数组,那么Python就不可能这样工作。(在C++术语中,所有变量都通过使用引用参数的方式传递……虽然这个术语在Python中可能会误导。)