所以我从我的 python 代码中看到了非常奇怪的行为,并且找不到我的问题的任何其他示例。根据我对 python 的了解,函数只能访问全局变量或内部变量。但是,我在下面的代码片段中发现,即使函数从未返回变量“密度”并且未全局声明变量“密度”,两个打印语句也会返回不同的结果。
def findHeight(density):
print density
height = integrateHeight(density, cutOff)
print density
return height
这确实是一个痛苦的事情,因为它会弄乱脚本中稍后的代码。
我使用的是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
改变其输入,请以不改变其输入的方式编写它。为此,您可能需要在函数中复制它,或者找到其他方法来执行计算而不改变对象。
关于Python 函数意外修改外部函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35067063/