我试着写一个闭包/嵌套函数来绘制许多类似的图。现在似乎并不是所有的值都被传递了,因为我尝试传递的一个变量得到了一个'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: local variable 'x_err‘referenced an’,我发现这个错误很奇怪,因为之前所有的变量都没有被检查过。
我是不是做错了什么,或者在python3中一个闭包可以传递多少个变量是有限制的?我运行的是python 3.6.9
发布于 2020-07-27 22:06:19
由于您在函数Plot(Path=os.getcwd(), **kwargs)中为x_err赋值,因此它会从外部作用域中隐藏该名称。您可以将变量传递给函数,也可以更改变量的名称,使其在PlotFunc和Plot中不同。
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')https://stackoverflow.com/questions/63116573
复制相似问题