在 python 中使用 plt.cm.Spectral 时,我有些困惑。 在检查了plt.cm.Spectral的类型后,我将模块plt.cm中的var Spectral视为类LinearSegmentedColormap的实例。 但是,我还发现代码 colors = plt.cm.Spectral(np.linspace(0, 1, 10)) 可以毫无错误地执行。这是让我困惑的一点,为什么可以调用类的实例,即后面跟着括号,里面有参数? 谢谢!
最佳答案
Python 对象如果实现 __call__
则可调用:
object.__call__(self[, args...])
Called when the instance is “called” as a function; if this method is defined,
x(arg1, arg2, ...)
is a shorthand forx.__call__(arg1, arg2, ...)
.
LinearSegmentedColormap
继承自实现 __call__
的 Colormap
:
https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/colors.py#L433
这使得 LinearSegmentedColormap
的实例可调用。
关于python - 为什么可以调用类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053123/