python函数的传参引用

python的函数调用中,将可变类型(list,numpy,等)传入函数做参数时,是传地址调用,这样在函数中修改变量的值时,会改变函数外变量的值

example1

import numpy as np

def func(vertices, scale):
    vertices[[1,3,5,7]] *= scale
    print(vertices)

vertices = np.asarray([0,1,2,3,4,5,6,7])
func(vertices, 3)
print(vertices)

[ 0  3  2  9  4 15  6 21]
[ 0  3  2  9  4 15  6 21]

改变了vertices变量的值。

如果不想改变怎么办

  • 用copy()属性,copy()会返回同样值的另外一个地址
  • 在函数中新建一个变量,

solution1

用copy()属性或函数

import numpy as np

def func(vertices, scale):
    vertices[[1,3,5,7]] *= scale
    print(vertices)

vertices = np.asarray([0,1,2,3,4,5,6,7])
func(vertices.copy(), 3)
print(vertices)

[ 0  3  2  9  4 15  6 21]
[0 1 2 3 4 5 6 7]

solution2

在函数中新建变量,不改变传入参数的值

import numpy as np

def func(vertices, scale):
    new_vertices = np.zeros(vertices.shape)
    new_vertices[[1,3,5,7]] = vertices[[1,3,5,7]] * scale
    print(vertices)
    print(new_vertices)

vertices = np.asarray([0,1,2,3,4,5,6,7])
func(vertices.copy(), 3)
print(vertices)
[0 1 2 3 4 5 6 7]
[ 0.  3.  0.  9.  0. 15.  0. 21.]
[0 1 2 3 4 5 6 7]

这里新建了一个new_vertices的变量

上一篇:javascript-Three.js:获取具有顶点变形目标的更新顶点


下一篇:1142 Maximal Clique (25 分)