如何使用字典 kwargs 作为可调用函数参数?

How can one use dictionary kwargs as callable function parameters?

我正在尝试学习如何通过字典使用 kwargs 作为函数输入。作为一个简单的学习示例,我正在尝试制作一个基本的 (x,y) 图,kwargs 可以为其指定曲线的颜色和一些其他绘图规格。

import numpy as np
import matplotlib.pyplot as plt

## generate data
f = lambda x : np.array([xi**2 for xi in x]) # function f(x)
x = np.linspace(0, 100)
y = f(x)

## define plotting routine
def get_plot(x, y, kwargs):
    """
    This plot will take multiple kwargs when successful.
    """
    plt.plot(x, y, **kwargs)
    plt.show()

我首先尝试使用一个 kwarg 生成绘图。这行得通。

plot_dict = dict(color='red')
get_plot(x, y, plot_dict)
>> plot appears 

然后我尝试使用两个 kwargs 生成绘图。这行不通。

plot_dict = dict(color='red', xlabel='this is the x-axis')
get_plot(x, y, plot_dict)
>> AttributeError: Unknown property xlabel

但我的印象是 xlabel is a kwarg 因为它是一个像颜色一样的可调用 arg。我的 misunderstanding/mistake 的来源是什么?

改为:

def get_plot(x, y, **kwargs):
    """
    This plot will take multiple kwargs when successful.
    """
    plt.plot(x, y, **kwargs)
    plt.show()

并像这样调用函数:get_plot(x, y, **plot_dict)

查看 this 教程以了解如何使用 **kwargs

简而言之**kwargs 所做的是将字典分解成一对 argument=value,即 kwarg1=val1, kwarg2=val2.. 而不是你做的手动。