闭包未传递值.python 3



我试图编写一个闭包/嵌套函数来绘制许多类似的图。现在,似乎并不是所有的值都被传递了,因为我得到了一个我试图传递的变量的"UnboundLocalError":

我的代码看起来像:

def PlotFunc(x_name, y_name, fig_name=None, x_scale=None, y_scale=None, x_err=None, y_err=None, x_label=None, y_label=None, Binning=False):
def Plot(Path=os.getcwd(), **kwargs):
x =  np.linspace(0,20)
y =  np.linspace(0,10)
if x_scale is not None:
xs = np.ones_like(x)
x = x/xs
if y_scale is not None:
ys = np.ones_like(y)
y=y/ys
if x_err is not None:            #The error is raised here
x_err =  np.ones_like(x)
if y_err is not None:
y_err = np.ones_like(y)
if fig_name is None:
fig_name = y_name+x_name+'.png'
#and then I would do the plots
return Plot
Plot_1 = PlotFunc('x', 'y', 'x-y-linspace.png', x_err=None, y_scale=np.ones(50), x_label=r'x', y_label=r'y')

运行Plot_1会引发一个错误"UnboundLocalError:本地变量"x_err"在赋值之前引用",我觉得这很奇怪,因为之前的所有变量都没有问题。

我是做错了什么,还是python3中的闭包中可以传递的变量数量有限制?我运行python 3.6.9

由于在函数Plot(Path=os.getcwd(), **kwargs)中为x_err指定了一个值,因此它会从外部范围遮蔽名称。您可以将变量传递给函数,也可以在PlotFuncPlot中将变量的名称更改为不相同。

def PlotFunc(x_name, y_name, fig_name=None, x_scale=None, y_scale=None, x_err=None, y_err=None, x_label=None, y_label=None, Binning=False):
def Plot(Path=os.getcwd(), **kwargs):
x =  np.linspace(0,20)
y =  np.linspace(0,10)
if x_scale is not None:
xs = np.ones_like(x)
x = x/xs
if y_scale is not None:
ys = np.ones_like(y)
y=y/ys
if x_err is not None:
x_err_other =  np.ones_like(x)
if y_err is not None:
y_err_other = np.ones_like(y)
if fig_name is None:
fig_name_other = y_name+x_name+'.png'
return Plot
Plot_1 = PlotFunc('x', 'y', 'x-y-linspace.png', x_err=None, y_scale=np.ones(50), x_label=r'x', y_label=r'y')

最新更新