简体   繁体   English

子类化和扩展numpy.ndarray

[英]Subclassing and extending numpy.ndarray

I need some basic data class representations and I want to use existing numpy classes, since they already offer great functionality. 我需要一些基本的数据类表示,我想使用现有的numpy类,因为它们已经提供了很好的功能。

However, I'm not sure if this is the way to do it (although it works so far). 但是,我不确定这是否是这样做的方法(虽然它到目前为止有效)。 So here is an example: 所以这是一个例子:

The Position class should act like a simple numpy.array , but it should map the attributes .x , .y and .z to the three array components. Position类应该像一个简单的numpy.array ,但它应该将属性.x.y.z映射到三个数组组件。 I overwrote the __new__ method which returns an ndarray with the initial array. 我覆盖了__new__方法,该方法返回带有初始数组的ndarray To allow access and modification of the array, I defined properties along with setters for each one. 为了允许访问和修改数组,我为每个属性定义了属性和setter。

import numpy as np


class Position(np.ndarray):
    """Represents a point in a 3D space

    Adds setters and getters for x, y and z to the ndarray.

    """
    def __new__(cls, input_array=(np.nan, np.nan, np.nan)):
        obj = np.asarray(input_array).view(cls)
        return obj

    @property
    def x(self):
        return self[0]

    @x.setter
    def x(self, value):
        self[0] = value

    @property
    def y(self):
        return self[1]

    @y.setter
    def y(self, value):
        self[1] = value

    @property
    def z(self):
        return self[2]

    @z.setter
    def z(self, value):
        self[2] = value

This seems however a bit too much code for such a basic logic and I'm wondering if I do it the "correct" way. 然而,对于这样的基本逻辑来说,这似乎有点太多代码,我想知道我是否采用“正确”的方式。 I also need bunch of other classes like Direction which will have quite a few other functionalities (auto-norm on change etc.) and before I start integrating numpy, I thought I ask you… 我还需要一些像Direction这样的其他类,它们会有很多其他的功能(改变后的自动规范等),在我开始集成numpy之前,我想我问你......

I would argue ndarray is the wrong choice here, you probably want a simple namedtuple. 我认为ndarray在这里是错误的选择,你可能想要一个简单的命名元组。

>>> import collections
>>> Position = collections.namedtuple('Positions', 'x y z')
>>> p = Position(1, 2, 3)
>>> p
Positions(x=1, y=2, z=3)

You could get the unpacking like so 你可以像这样拆包

>>> x, y, z = p
>>> x, y, z
(1, 2, 3)
>>>

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

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