在python中使用plt.cm.Spectral时,我感到有些困惑。 检查 plt.cm.Spectral 的类型后,我将模块plt.cm中的var Spectral视为LinearSegmentedColormap类的实例。 但是,我也看到代码 colors = plt.cm.Spectral(np.linspace(0,1,10)) 可以无误地执行。这一点让我感到困惑,为什么可以调用一个类的实例,即后跟带有params的括号? 谢谢!
答案 0 :(得分:3)
如果Python对象实现__call__
:
object.__call__(self[, args...])
当实例被“调用”为函数时调用;如果定义了此方法,则
x(arg1, arg2, ...)
是x.__call__(arg1, arg2, ...)
的缩写。
LinearSegmentedColormap
继承自实施Colormap
的{{1}}:
https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/colors.py#L433
这使得__call__
的实例可以调用。