python之传值与传引用

python版本3.8.1

1.基本类型是传值

复制一份,不影响原来的变量的值

height = 1.58
def predict_height(height):
	"""预测将来的身高"""
	height = height + 0.3
	return height

future_height = predict_height(height)

print(future_height)   #1.8800000000000001
print(height)          #1.58

#存储位置是不一样的
print(id(future_height))  #2016745716944
print(id(height))         #2016745717008

2.复杂类型是传引用

传过去是变量的内存地址,所以要修改就都修改了

heights = [1.58,1.56,1.87,1.72,1.75]
def predict(heights):
	for index,h in enumerate(heights):
		heights[index] = h + 0.3
	return heights

predict_heights = predict(heights)
print(heights)         #[1.8800000000000001, 1.86, 2.17, 2.02, 2.05]
print(predict_heights) #[1.8800000000000001, 1.86, 2.17, 2.02, 2.05]

#存储位置是一样的
print(id(heights))         #2771605977856
print(id(predict_heights)) #2771605977856

3.复杂类型如何传值

heights = [1.58,1.56,1.87,1.72,1.75]
def predict(heights):
	for index,h in enumerate(heights):
		heights[index] = h + 0.3
	return heights

predict_heights = predict(heights[:])
print(heights)         #[1.58, 1.56, 1.87, 1.72, 1.75]
print(predict_heights) #[1.8800000000000001, 1.86, 2.17, 2.02, 2.05]

#存储位置是不一样的
print(id(heights))         #2035873419584
print(id(predict_heights)) #2035873419520
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值