![](/img/trans.png)
[英]How to save 2D float numpy arrays losslessly into a grayscale image while preserving resolution?
[英]How to make 2D arrays with numpy while preserving inheritance
我有一個多邊形 class ,它使用 2d ndarray 來存儲它的點。 class 中的每個點都是向量 class 的一個實例,這個向量 class 繼承了 numpy 的 ndarray。 Am currently using numpy.vstack to append points, but the problem is that my vector instances are converted to their parent class, numpy.ndarray.
import numpy as np
class Vector(np.ndarray):
def __new__(cls, *args, **kwargs):
arr = np.asarray([args[0], args[1], args[2]]).view(cls)
arr = arr.astype('float64')
return arr
class Polygon(object):
def __init__(self):
self.points = np.array([]).reshape(0, 3)
def append_point(self, point):
self.points = np.vstack([self.points, point])
poly = Polygon()
vec1 = Vector(1, 2, 3)
print(type(vec1)) # output: <class '__main__.Vector'>
poly.append_point(vec1)
print(poly.points) # output: [[1. 2. 3.]]
print(type(poly.points[0])) # output: <class 'numpy.ndarray'>
有更好的方法嗎?
如果要保留子類,我認為您需要覆蓋__array_function__
方法:
class Vector(np.ndarray):
def __new__(cls, *args, **kwargs):
arr = np.asarray([args[0], args[1], args[2]]).view(cls)
arr = arr.astype('float64')
return arr
def __array_function__(self, func, types, args, kwargs):
x,y = args[0]
return func([x.view(np.ndarray), y.view(np.ndarray)], **kwargs).view(Vector)
這會給
poly = Polygon()
vec1 = Vector(1, 2, 3) # Vector([1., 2., 3.])
poly.append_point(vec1)
poly.points # Vector([[1., 2., 3.]])
poly.points[0] # Vector([1., 2., 3.])
您使用Vector
調用的任何 function 都將被__array_function__
攔截(ufuncs 除外)。 盡管這適用於您的特定情況,但您需要對其進行修改以使其更適用於任何類型的輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.