我声明了一个变量x
,它是函数output = model(x)
的输入。调用后x
获得与output
变量相同的值。我原以为呼叫前后x
应该相同,但事实并非如此。代码的行为就像函数model
中的output
变量和局部变量是指向x
的指针一样。你能解释一下这种行为吗?我从未在Fortran、C/C++和Matlab中遇到过类似的东西。下面是我的python代码示例
import numpy as np def model(aux): for i in range(0,len(aux)): aux[i] = np.sin( aux[i] ) + 1 return aux length = 5 x = np.linspace(0,1,length) print('\n X variable BEFORE the function call \n') for i in range(0,length): print('x [',i,'] =', x[i]) output = model(x) print('\n X variable AFTER the function call \n') for i in range(0,length): print('x [',i,'] =', x[i]) print('\n Output variable AFTER the function call \n') for i in range(0,length): print('output [',i,'] =', output[i])
这里的广告是我得到的:
X variable BEFORE the function call x [ 0 ] = 0.0 x [ 1 ] = 0.25 x [ 2 ] = 0.5 x [ 3 ] = 0.75 x [ 4 ] = 1.0 X variable AFTER the function call x [ 0 ] = 1.0 x [ 1 ] = 1.247403959254523 x [ 2 ] = 1.479425538604203 x [ 3 ] = 1.6816387600233342 x [ 4 ] = 1.8414709848078965 Output variable AFTER the function call output [ 0 ] = 1.0 output [ 1 ] = 1.247403959254523 output [ 2 ] = 1.479425538604203 output [ 3 ] = 1.6816387600233342
X变量BEFORE和AFTER不应该相同吗?