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