2017-09-30 3 views
1

Ich wollte negative Indizierung in Arrays verhindern.TypeError: Erforderliches Argument nicht gefunden __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() 

Wenn ich eine Instanz ich einen Fehler bekam:

in <module> 
    a=Item_I() 

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

Antwort

1

Das ist, weil Sie aus einer Klasse, Unterklasse, die __new__ verwendet neue Instanzen zu erstellen und numpy.ndarray requires several arguments in __new__, bevor es sogar __init__ zu nennen versucht:

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. 

Die NumPy-Dokumentation enthält jedoch eine ganze Seite für Subclassing ndarray.

Sie sollten wahrscheinlich nur verwenden view und Myarray statt Subklassen von Myarray:

tab=np.load("file.txt") 
tab.view(Myarray) 
Verwandte Themen