为什么numpy.r_使用括号而不是括号? [英] Why does numpy.r_ use brackets instead of parentheses?
问题描述
Numpy.r _ 、. c_和.s_是我遇到的仅有的Python函数,它们使用方括号而不是括号作为参数.为什么会这样呢?这些功能有什么特别之处吗?我可以制作自己的使用方括号的功能(不是我想要的;只是出于好奇)?
Numpy.r_, .c_ and .s_ are the only Python functions I've come across that take arguments in square brackets rather than parentheses. Why is this the case? Is there something special about these functions? Can I make my own functions that use brackets (not that I want to; just curious)?
例如,正确的语法是:
np.r_['0,2', [1,2,3], [4,5,6]]
我希望它是:
np.r_('0,2', [1,2,3], [4,5,6])
推荐答案
可以制作任何Python类,使其实例接受一个或两个符号:它将通过实现称为__call__
的函数接受括号,并通过实现将括号括起来__getitem__
.
Any Python class can be made so that its instances accept either or both notation: it will accept parens by implementing a function called __call__
, and brackets by implementing __getitem__
.
np.r_
恰好是一个实现__getitem__
的类,它比平时做的更好.也就是说,r_
的类(称为np.lib.index_tricks.RClass
)执行以下操作:
np.r_
happens to be of a class that implements __getitem__
to do fancier things than its usual. That is, the class of r_
(called np.lib.index_tricks.RClass
) does something like this:
class RClass:
def __getitem__(self, item):
# r_ fancyness
这样做是为了使它可以利用切片符号-例如,当您有一个列表(或np数组或实现此协议的任何其他对象)时,您这样做:
Likely, this was done so that it can take advantage of slice notation - eg, when you have a list (or np array or any other object implementing this protocol) l
, and you do:
l[:5]
,Python自动创建一个slice
对象以传递给__getitem__
.
, Python automatically creates a slice
object to pass to __getitem__
.
此语法不与__call__
一起使用-用户必须通过执行l(slice(5))
显式创建切片.
This syntax doesn't work with __call__
- a user would have to create the slice explicitly, by doing l(slice(5))
.
请注意,__call__
可以接受您喜欢的任何参数.而__getitem__
始终只使用一个参数:当您执行类似my_array[1:3, 2:5]
的操作时,Python会传入一个单独的 tuple 切片.但是,正如您在r_
中看到的那样,内容并不仅限于数字和切片-与任何其他函数类似,Python会很乐意传入任何对象并将其留给类以弄清楚其含义.
Note that __call__
can take whatever arguments you like; while __getitem__
always takes exactly one argument: when you do something like my_array[1:3, 2:5]
, Python passes in a single tuple of slices. But, as you see with r_
, the contents aren't restricted to numbers and slices - similarly to any other function, Python will happily pass in any object and leave it to the class to work out what it means.
这篇关于为什么numpy.r_使用括号而不是括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!