2017-09-30 44 views
1

我旨在防止數組中的負向索引。TypeError:未找到必需的參數__getitem__ numpy

import numpy as np 

class Myarray (np.ndarray): 
    def __getitem__(self,n): 
     if n<0: 
      raise IndexError("...") 
     return np.ndarray.__getitem__(self,n) 

class Items(Myarray): 
    def __init__(self): 
     self.load_tab() 

class Item_I(Items): 
    def load_tab(self): 
     self.tab=np.load("file.txt") 

a=Item_I() 

當我創建一個實例我得到了一個錯誤:

in <module> 
    a=Item_I() 

TypeError: Required argument 'shape' (pos 1) not found 

回答

1

那是因爲你從使用__new__創建新實例和numpy.ndarray requires several arguments in __new__甚至試圖調用__init__前一類的子類:

Parameters for the __new__ method

shape : tuple of ints

Shape of created array. 

dtype : data-type, optional

Any object that can be interpreted as a numpy data type. 

buffer : object exposing buffer interface, optional

Used to fill the array with data. 

offset : int, optional

Offset of array data in buffer. 

strides : tuple of ints, optional

Strides of data in memory. 

order : {‘C’, ‘F’}, optional

Row-major (C-style) or column-major (Fortran-style) order. 

但是,NumPy文檔包含Subclassing ndarray的整個頁面。

你或許應該只使用viewMyarray除了繼承自Myarray

tab=np.load("file.txt") 
tab.view(Myarray) 
相關問題