gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:01 24 4
gpt4 key购买 nike

我的目的是防止数组中出现负索引。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com