[問題] numpy subclassing ndarray

看板Python作者 (wakaka)時間10年前 (2015/04/17 06:02), 10年前編輯推噓0(001)
留言1則, 1人參與, 最新討論串1/1
我目前嘗試創一個subclass of numpy.ndarray 希望他可以有的功能是: 1. 有dimension限制 2. 可以限制大小 3. 無資料型態限制 目前狀況: (1) dtype會被限制,如果dtype與arg: arr型態不一致, 會回傳一array但值錯誤 class Vector1D(numpy.ndarray): def __new__(cls, arr): return np.ndarray.__new__(cls, shape=(3), dtype=float, buffer=numpy.asarray(arr)) e.g: > s = Vector1D([1,2,3]) > print (s) [ 4.94065646e-324 9.88131292e-324 1.48219694e-323] (2) __new__改用np.asarray() 但這變成我沒有辦法去限制dimension與大小 class Vector1D(cls, arr): def __new__(cls, arr): return np.asarray(arr).view(cls) 請問我應該怎麼修改才能符合我的目的? 感謝各位 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.56.185 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1429221744.A.31A.html ※ 編輯: walelile (1.171.56.185), 04/17/2015 06:03:16 ※ 編輯: walelile (1.171.56.185), 04/17/2015 06:04:22 ※ 編輯: walelile (1.171.56.185), 04/17/2015 06:09:50

04/22 02:52, , 1F
解決方式 (2)return np.array(arr[0:2]).view(cls)
04/22 02:52, 1F
文章代碼(AID): #1LC35mCQ (Python)
文章代碼(AID): #1LC35mCQ (Python)