numpy.r_不是一个函数。它是什么? [英] numpy.r_ is not a function. What is it?

查看:534
本文介绍了numpy.r_不是一个函数。它是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据上 numpy.r _ 这里,它是不是一个函数,所以不需要参数。

如果它不是一个函数,适用于功能的术语,如 numpy.r _

解决方案

这是一个类实例(又名一个对象):

  In [2]:numpy.r_ 
Out [2 ]:< numpy.lib.index_tricks.RClass at 0x1923710>

一个类是一个用来定义一个不同的类型的构造 - 因为这样的类允许自己的实例。每个实例可以有属性(成员/实例变量和方法)。

类可以有一个方法是 __ getitem __ 方法,只要将 [something,something ... something] 追加到实例的名称,就会调用它。在 numpy.r _ 实例中,该方法返回一个numpy数组。



以下面的类为例:

$ p $ class myClass(object)
def __getitem __(self,i)
return i * 2

查看上述类的输出结果:
<在[1]中:a = myClass()

In [2]:a [3]
Out [2]:6

[3]:a [3,4]
Out [3]:(3,4,3,4)

我调用myClass的 __ getitem __ 方法(通过 [] 括号)和 __ getitem __ 方法正在返回(在这种情况下,列表的内容是* 2) - 它不是类/实例表现为一个函数 - 它是被调用的 myClass 实例的 __ getitem __ 函数。



最后一点,你会注意到要实例化 myClass 我必须做 a = myClass( )而得到 RClass 您使用的实例 numpy.r _ 这是因为numpy实例化 RClass 并将其绑定到名称numpy.r_本身。 这是numpy的源代码。在我看来,这是相当丑陋和令人困惑的!


According to the numpy/scipy doc on numpy.r_ here, it is "not a function, so takes no parameters".

If it is not a function, what is the proper term for "functions" such as numpy.r_?

解决方案

It's a class instance (aka an object):

In [2]: numpy.r_
Out[2]: <numpy.lib.index_tricks.RClass at 0x1923710>

A class is a construct which is used to define a distinct type - as such a class allows instances of itself. Each instance can have properties (member/instance variables and methods).

One of the methods a class can have is the __getitem__ method, this is called whenever you append [something,something...something] to the name of the instance. In the case of the numpy.r_ instance the method returns a numpy array.

Take the following class for example:

class myClass(object)
    def __getitem__(self,i)
    return i*2

Look at these outputs for the above class:

In [1]: a = myClass()

In [2]: a[3]
Out[2]: 6

In [3]: a[3,4]
Out[3]: (3, 4, 3, 4)

I am calling the __getitem__ method of myClass (via the [] parentheses) and the __getitem__ method is returning (the contents of a list * 2 in this case)- it is not the class/instance behaving as a function - it is the __getitem__ function of the myClass instance which is being called.

On a final note, you will notice that to instantiate myClass I had to do a = myClass() whereas to get an instance of RClass you use numpy.r_ This is because numpy instantiates RClass and binds it to the name numpy.r_ itself. This is the relevant line in the numpy source code. In my opinion this is rather ugly and confusing!

这篇关于numpy.r_不是一个函数。它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆