Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

python - Why does numpy.r_ use brackets instead of parentheses?

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)?

For example, the proper syntax is:

    np.r_['0,2', [1,2,3], [4,5,6]]

I would have expected it to be:

    np.r_('0,2', [1,2,3], [4,5,6])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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_ 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

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 automatically creates a slice object to pass to __getitem__.

This syntax doesn't work with __call__ - a user would have to create the slice explicitly, by doing l(slice(5)).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...