python - 类型错误 : Required argument not found __getitem__ numpy

标签 python arrays python-3.x class 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

最佳答案

那是因为您从使用 __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)

关于python - 类型错误 : Required argument not found __getitem__ numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503572/

相关文章:

python - 使用 Selenium 或请求填写表格

python - 在 64 位 Windows 上从哪里获取和安装 crypto.dll

python - 如何编写一个函数通过在 python 中清理来缩短我的列表

Python subprocess.call() 为每个 stdout 和 stderr 行添加前缀

python - 从嵌套字典中递归删除 None 值或 None 键

python - 使用 Python 2.7 和 openpyxl 在 Excel 中删除单元格

c - C 中的打印数组函数仅打印第一个元素

javascript - 在 console.log 中打印函数的输出

javascript - 在函数完成之前返回数组和 Angular JS

python-3.x - Pickle 不能 pickle _thread.lock 对象