python - 为什么可以调用类的实例?

标签 python

在 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 for x.__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/

相关文章:

python - Python的python-daemon和daemonize有什么区别?

python - 为行中的每个值创建一个新列

python - 分配给 python : a bug? 中的可变元组组件是一个特性吗?

python - Twisted + Gtk - 关闭无法正常工作

python - 为什么我无法在 Heroku 上的 Python/Flask/Jinja2 中使用 url_for 提供静态文件?

python - 使用 PETL 解析 XML

python - BeautifulSoup:根据前面标签的内容打印 div

php - 从 php 调用时 Python mysql 语句返回错误

Python:我的进程中导入了哪些模块?

Python字典太满还是其他原因?