ValueError: PyObject is NULL when running some test cases on the dynamic array using python?

问题描述 投票:0回答:0

那是我在 python 中使用类型实现的动态数组:

import ctypes

class DynamicArray:

  def __init__(self,):
    self.n = 0 # the current number of elements added to the array
    self.capacity = 1 # Initial capacity of the dynamic array is one 
    self.array    = self.make_array(self.capacity)

  def add_element(self,element):
    # First check whether the array is full or not
    if self.n == self.capacity:
      self.resize(2*self.capacity)
    
    self.array[self.n] = element
    self.n +=1 

    return 

  def resize(self,new_capacity):
    new_array = self.make_array(new_capacity)

    for i in range(self.n):
      new_array[i] = self.array[i]

    self.array = new_array
    self.capacity = new_capacity
    return 

  def make_array(self,capacity):
    return (capacity * ctypes.py_object)()

  def get_array(self):
    return list(self.array)

运行以下测试用例后:

dynamic_r = DynamicArray()
dynamic_r.add_element(4)
dynamic_r.get_array()
dynamic_r.add_element(9)
dynamic_r.get_array()
dynamic_r.add_element(10)
dynamic_r.get_array()

我明白了

ValueError: PyObject is NULL

需要注意的是,我并不是每次运行代码都出现这个错误

python ctypes dynamic-arrays
© www.soinside.com 2019 - 2024. All rights reserved.