2017-09-30 25 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) 
相关问题