简体   繁体   中英

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.

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. I overwrote the __new__ method which returns an ndarray with the initial array. To allow access and modification of the array, I defined properties along with setters for each one.

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…

I would argue ndarray is the wrong choice here, you probably want a simple namedtuple.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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