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的变量

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值