[英]Python function unexpectedly modifies variable in outer function
所以我從我的python代碼中看到了非常奇怪的行為,並且找不到我的問題的任何其他示例。 從我讀過的python中,函數只能訪問全局或內部變量。 但是,我在下面的代碼片段中發現,即使變量“density”從未被函數返回並且未全局聲明,兩個print語句也會返回不同的結果。
def findHeight(density):
print density
height = integrateHeight(density, cutOff)
print density
return height
這是a **中的一個真正的痛苦,因為它后來在腳本中搞亂了代碼。
我使用的是python 2.7.6,我的函數定義如下:
def integrateHeight(data, cutOff):
# accumulate data values and rescale to fit interval [0,1]
# Calculate bin widths (first one is a different size from the others)
data[0,1] = -2*data[0,0]*data[0,1]
data[1:,1] = (data[2,0] - data[1,0])*data[1:,1]
# accumulate distribution and divide by the total
data[:,1] = np.cumsum(data[:,1]) / data[:,1].sum()
# Assign a default height value
height = data[0,0]
# store the first height,fraction pair
prev = data[0]
# loop through remaining height,fraction pairs
for row in data[1:]:
# check that the cut-off is between two values
if row[1] > cutOff >= prev[1]:
# Interpolate between height values
height = interpolate(cutOff, prev[::-1], row[::-1])
# exit the loop when the height is found
break
# store the current height,fraction value
prev = row
return height
該特定腳本應該采用分布,累積它,並找到對應於累積分布的特定部分的高度。
未修改變量 ,正在修改傳遞給integrateHeight
的對象 。 這很正常。 如果您不希望integrateHeight
改變其輸入,請以不改變其輸入的方式編寫它。 為此,您可能需要在函數中復制它,或者在不改變對象的情況下找到執行計算的其他方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.