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

Use of **kwargs in a function as variable?

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

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(您不能为可变数量的本地人动态分配 space,因此实际上不可能将 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 中指定关键字参数,然后将它们传递给 plotly 函数。

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

并可选择提供默认参数:

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

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

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