Class 迭代内部 numpy 数组?任务?

Class iteration over internal numpy array ? Assignment?

如何使 class 通过其内部 numpy 数组进行迭代: 只是想法行不通:

class ABC:

  def __init__(self):
     self.ary = np.zeros(50)

  def __iter__(self): return np.nditer(self.ary)
  def next(self): ...??..

还有如何让作业也起作用:

abc = ABC()
abc[5] = 12
abc[7:9] 0

来自文档,

iterator.__next__():

Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

对于容器 class 的 settinggetting 值,您需要实施 __getitem____setitem__

对于您的示例代码

class ABC():
  def __init__(self):
     self.ary = np.zeros(50)
     self.index = self.ary.shape[0]

  def __iter__(self): 
     return np.nditer(self.ary)

  def next(self):
      if self.index == 0:
          raise StopIteration
      self.index = self.index - 1
      return self.data[self.index]

  def _check_indx(self, idx):
      if abs(idx) >= self.ary.shape[0]:
          raise IndexError(f"Invalid Index {idx} for array with shape {self.ary.shape}")

  def __setitem__(self, idx, value):
      self._check_indx(idx)
      self.ary[idx] = value

  def __getitem__(self, idx):
      self._check_indx(idx)
      return self.ary[idx]