在函数中使用**kwargs作为变量?



我有一个绘制地图的函数。

def plot(country, year1, year2, month, obs,**kwargs):

我有一个plotly express函数来绘制散点图框:

fig = px.scatter_mapbox(df_to_plot, 
lat="LATITUDE",#latitude of the station 
lon="LONGITUDE", #longitude of the station
hover_name = "NAME", #when hovered, show the name of the station
color = "coef", #color differs by coef
zoom=zoom, #default zoom size.
mapbox_style = mapbox_style, #style of the plot.
color_continuous_scale=color_continuous_scale, #scale of the colorbar, red to gray countinuous.
...

这里,我想传递zoom, mapbox_style, color_continuous_scale的参数。

然而,当我调用函数并传递参数时:
fig =plot("India", 1980, 2020, 1, 
obs = 10,
zoom = 2,
mapbox_style="carto-positron",
color_continuous_scale=color_map)

我得到一个错误:名称'zoom'没有定义。

也许我用错了**Kwargs。如何手动传递参数并在函数中使用它们?

如果这些是plot的强制参数,只需像所有其他参数一样接受名称参数;如果您愿意,可以将它们放在*后面,使它们仅为关键字(没有名称,则使其余部分仅为关键字);有了名称,它将允许任意的附加位置参数,所以在这里可能不是一个好主意):

def plot(country, year1, year2, month, obs, *, zoom, mapbox_style, color_continuous_scale):

plot的主体不变。

如果这些参数并不总是需要的,并且在不同的代码路径中有时需要各种各样的参数,您只需要知道**kwargs将它们收集为字符串关键字的dict(您不能动态地为变量数量的局部分配空间,因此实际上使zoom有条件地定义为本地范围内的原始名称是不可能的),因此查找额外的名称的方式与dict相同,例如:

fig = px.scatter_mapbox(df_to_plot, 
lat="LATITUDE",#latitude of the station 
lon="LONGITUDE", #longitude of the station
hover_name="NAME", #when hovered, show the name of the station
color="coef", #color differs by coef
zoom=kwargs['zoom'], #default zoom size.
mapbox_style=kwargs['mapbox_style'], #style of the plot.
color_continuous_scale=kwargs['color_continuous_scale'], #scale of the colorbar, red to gray countinuous.

,如果调用者未能提供它们,则在查找时将获得KeyError

您可以像这样将plot函数的所有关键字参数传递给plotly函数:

px.scatter_mapbolx(..., **kwargs)

不需要指定每个关键字参数

也可以在plot中指定关键字参数,然后将它们传递给plot函数。

def plot(..., zoom, mapbox_style, ...):

并可选地给出默认参数:

def plot(..., zoom=1, mapbox_style=None, ...):

但是不要把这两种方法混在一起。如果在plot定义中使用**kwargs作为参数,则最后使用**kwargs调用plotly函数。

如果在plot函数定义中使用单个关键字参数,则将它们作为单个关键字参数传递给plot函数。

最新更新