简体   繁体   English

用括号而不是方括号索引语法是什么意思?

[英]What does indexing syntax by parentheses instead of square brackets mean?

In Python (matplotlib package), I created an object of ListedColormap using the following line:在 Python(matplotlib 包)中,我使用以下行创建了 ListedColormap 的ListedColormap

listed_color_map = ListedColormap(('red', 'green', 'blue'))

Then I saw a code retrieving the colors (eg green) like this:然后我看到一个检索 colors(例如绿色)的代码,如下所示:

listed_color_map(1)

Calling the previous line returns:调用上一行返回:

(0.0, 0.5019607843137255, 0.0, 1.0) (0.0, 0.5019607843137255, 0.0, 1.0)

I have never seen this kind of Indexing with parenthesis (square brackets don't work here).我从未见过这种带括号的索引(方括号在这里不起作用)。 This looks for me exactly as like as calling a method.这对我来说就像调用一个方法一样。 What is this syntax of retrieving the values from the ListedColorMap exactly?ListedColorMap准确检索值的语法是什么?

And it can be also called like this:它也可以这样称呼:

listed_color_map = ListedColormap(('red', 'green', 'blue'))(1)

This seems to me just like calling a method immediately after calling the constructor which is a bit weird for me (in C family there is no equivalent to this).在我看来,这就像在调用构造函数后立即调用一个方法,这对我来说有点奇怪(在 C 系列中没有与此等效的方法)。

It means that the instances are "callable" ie the class (or a parent of it) implements the __call__ method.这意味着实例是“可调用的”,即 class(或其父级)实现了__call__方法。 This dunder method allows to "call" the instances with the parantheses.这个dunder 方法允许用括号“调用”实例。

For your very example, it turns out the parent of ListedColormap class, which is ColorMap class, implements dunder call method.对于您的示例,事实证明ListedColormap class 的父级,即ColorMap class,实现了 dunder 调用方法。 We can see the source code of ListedColormap and its parent that implements that interface.我们可以看到ListedColormap的源代码及其实现该接口的级。

The doc of the __call__ function reads __call__ function 的文档读取

Returns
-------
Tuple of RGBA values if X is scalar, otherwise an array of
RGBA values with a shape of ``X.shape + (4, )

where X is your input, 1. In your second example, you are more or less doing the same thing: you're generating an instance of ListedColormap class and immediately "call"ing it with a scalar argument.其中X是您的输入,1. 在您的第二个示例中,您或多或少在做同样的事情:您正在生成ListedColormap class 的实例,并立即使用标量参数“调用”它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM