我如何评估函数外的局部变量?

时间:2016-10-28 01:09:45

标签: netcdf local-variables

在这部分代码中,我定义了一个函数来对感兴趣的区域进行子集化。但是,我希望稍后在另一个函数中使用变量latselect和lonselect。所以我有:

def DatasetToSubset(file, LatUpbound, LatLowBound, LonUpBound, LonLowBound):
    nc=netCDF4.Dataset(file)  
    lats=nc.variables['lat'][:]; lons=nc.variables['lon'][:]  
    latselect=np.logical_and(lats > LatLowBound, lats < LatUpBound)    
    lonselect=np.logical_and(lon > LonLowBound, lon < LonUpBound)  
    data=nc.variables['Runoff'][1000, latselect, lonselect]   
    return data; return latselect; return lonselect

1 个答案:

答案 0 :(得分:1)

一旦函数到达return语句,它就会返回该值并立即终止,这意味着后续的两个语句将永远不会执行。您可以将这三个值作为元组返回,如此

def DatasetToSubset(file, LatUpbound, LatLowBound, LonUpBound, LonLowBound):
    nc=netCDF4.Dataset(file)  
    lats=nc.variables['lat'][:]; lons=nc.variables['lon'][:]  
    latselect=np.logical_and(lats > LatLowBound, lats < LatUpBound)    
    lonselect=np.logical_and(lon > LonLowBound, lon < LonUpBound)  
    data=nc.variables['Runoff'][1000, latselect, lonselect]   
    return (data, latselect, lonselect)

当你调用这个函数时,你可以像这样解压缩三个值

(a, b, c) = DatasetToSubset(...)

a将保留data的{​​{1}},b的{​​{1}}以及latselect的{​​{1}}的值。