numpy 实现为 C 代码和 Python 代码的混合。源代码可在github 上浏览,并可作为git 存储库下载。但是挖掘C 源代码需要一些工作。很多文件被标记为.c.src,这意味着它们在编译之前要经过一层或多层perprocessing。
Python 也是用 C 和 Python 混合编写的。所以不要试图把事情强加到 C++ 术语中。
利用您的 MATLAB 经验可能会更好,并进行调整以允许使用 Python。 numpy 有许多 Python 之外的怪癖。它使用 Python 语法,但因为它有自己的 C 代码,所以它不仅仅是一个 Python 类。
我使用Ipython 作为我通常的工作环境。有了它,我可以使用foo? 查看foo 的文档(与Python help(foo) 和foo?? 相同以查看代码——如果它是用Python 编写的(如MATLAB/Octave type(foo))
Python 对象具有属性和方法。还有properties 看起来像属性,但实际上使用方法来获取/设置。通常你不需要知道属性和属性之间的区别。
x.ndim # as noted, has a get, but no set; see also np.ndim(x)
x.shape # has a get, but can also be set; see also np.shape(x)
Ipython 中的x.<tab> 向我展示了ndarray 的所有补全。有4*18。有些是方法,有些是属性。 x._<tab> 显示了更多以__ 开头的内容。这些是“私人的”——不是为了公共消费,但这只是语义。您可以查看它们并在需要时使用它们。
副手x.shape 是我设置的唯一ndarray 属性,即便如此,我通常使用reshape(...) 代替。阅读他们的文档以查看差异。 ndim 是维数,直接改没意义。是len(x.shape);改变形状改变ndim。同样x.size 不应该是你直接改变的东西。
其中一些属性可以通过函数访问。 np.shape(x) == x.shape,类似于 MATLAB size(x)。 (MATLAB 没有. 属性语法)。
x.__array_interface__ 是一个方便的属性,它提供了一个包含许多属性的字典
In [391]: x.__array_interface__
Out[391]:
{'descr': [('', '<f8')],
'version': 3,
'shape': (50,),
'typestr': '<f8',
'strides': None,
'data': (165646680, False)}
ndarray(shape, dtype=float, buffer=None, offset=0,
strides=None, order=None) 的文档,__new__ 方法列出了这些属性:
`Attributes
----------
T : ndarray
Transpose of the array.
data : buffer
The array's elements, in memory.
dtype : dtype object
Describes the format of the elements in the array.
flags : dict
Dictionary containing information related to memory use, e.g.,
'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
flat : numpy.flatiter object
Flattened version of the array as an iterator. The iterator
allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
assignment examples; TODO).
imag : ndarray
Imaginary part of the array.
real : ndarray
Real part of the array.
size : int
Number of elements in the array.
itemsize : int
The memory use of each array element in bytes.
nbytes : int
The total number of bytes required to store the array data,
i.e., ``itemsize * size``.
ndim : int
The array's number of dimensions.
shape : tuple of ints
Shape of the array.
strides : tuple of ints
The step-size required to move from one element to the next in
memory. For example, a contiguous ``(3, 4)`` array of type
``int16`` in C-order has strides ``(8, 2)``. This implies that
to move from element to element in memory requires jumps of 2 bytes.
To move from row-to-row, one needs to jump 8 bytes at a time
(``2 * 4``).
ctypes : ctypes object
Class containing properties of the array needed for interaction
with ctypes.
base : ndarray
If the array is a view into another array, that array is its `base`
(unless that array is also a view). The `base` array is where the
array data is actually stored.
所有这些都应该被视为属性,尽管我不认为numpy 实际上使用了property 机制。一般来说,它们应该被认为是“只读的”。除了shape,我只记得更改了data(指向数据缓冲区的指针)和strides。