python fast.ai 函数中不在函数定义中的参数?

数据挖掘 Python 朱庇特 法泰
2022-03-11 00:27:33

我遇到过使用不在函数定义中的参数的函数调用。我想知道它是如何工作的(即编译器如何解释它)。

例如,这个函数调用:

 interp.plot_confusion_matrix(figsize=(12,12), dpi=60)

使用变量“figsize”和“dpi”,但它们都没有出现在 : 的定义中plot_confusion_matrixhelp(interp.plot_confusion_matrix)给出:

plot_confusion_matrix(normalize: bool = False, title: str = 'Confusion matrix', 
cmap: Any = 'Blues', norm_dec: int = 2, slice_size: int = None, **kwargs) -> None 
method of fastai.vision.learner.ClassificationInterpretation instance
    Plot the confusion matrix, with `title` and using `cmap`.

如果“figsize”和“dpi”不是函数的参数,为什么在函数调用中使用它们不是错误?这在 python 中是如何工作的?

1个回答

这些参数由**kwargs函数定义处理。您可以查看fastai repo 中的代码如何处理此问题并**kwargs在函数定义中查找。
可以在 SO 上找到有关其工作原理的一些解释:https ://stackoverflow.com/questions/3394835/use-of-args-and-kwargs 。