[英]Subclassing and extending numpy.ndarray
我需要一些基本的數據類表示,我想使用現有的numpy類,因為它們已經提供了很好的功能。
但是,我不確定這是否是這樣做的方法(雖然它到目前為止有效)。 所以這是一個例子:
Position
類應該像一個簡單的numpy.array
,但它應該將屬性.x
, .y
和.z
映射到三個數組組件。 我覆蓋了__new__
方法,該方法返回帶有初始數組的ndarray
。 為了允許訪問和修改數組,我為每個屬性定義了屬性和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
然而,對於這樣的基本邏輯來說,這似乎有點太多代碼,我想知道我是否采用“正確”的方式。 我還需要一些像Direction
這樣的其他類,它們會有很多其他的功能(改變后的自動規范等),在我開始集成numpy之前,我想我問你......
我認為ndarray在這里是錯誤的選擇,你可能想要一個簡單的命名元組。
>>> import collections
>>> Position = collections.namedtuple('Positions', 'x y z')
>>> p = Position(1, 2, 3)
>>> p
Positions(x=1, y=2, z=3)
你可以像這樣拆包
>>> x, y, z = p
>>> x, y, z
(1, 2, 3)
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.