如何在以另一个 C 扩展作为输入的 C 扩展中设置可变变量?

How can I set a mutable variable in C extensions which takes another C extension as input?

让我们假设有一些 class 像这些:

cdef class parent:
  cdef public:
    int trait1
  def __init__(self, num1):
    self.trait1 = num1

cdef class child(parent):
  cdef public:
    int trait2
  def __init__(self, num1, num2):
    super().__init__(num1)
    self.trait2 = num2

cdef class new_parent:
  cdef public:
    float new_trait
  def __init__(self, num):
    self.new_trait = num

现在我想要另一个像这样的class:

cdef class gui:
  cdef public:
    parent agent
  def __init__(self, agent):
    self.agent = agent
  def change_parent(self, new_agent): # new_agent could be any of [child, parent, new_parent]
    self.agent = new_agent
    print(self.module)

gui class 中,我声明了一个变量,它可以将 class 作为输入(在 [parent, new_parent, child] 之间)。问题是,如果我想在 gui.change_parent 函数中将 gui.agent 更改为另一个 class,则会出现此错误:

TypeError: Cannot convert _cython_magic_b6858e13e41432c14dc63fbb10e81472.new_parent to _cython_magic_b6858e13e41432c14dc63fbb10e81472.parent

我在 python 中开发了相同的代码,但是这样的错误从未发生过,因为我不需要对 class 变量进行静态类型化。那么我应该怎么做才能在 cython 中将 gui.agent 修改为另一个 classes?有解决办法吗?

您将 agent 的类型定义为 parent,这允许它是 parent 或任何派生类型。 new_parent 不是 parent 类型,也不是从 parent 派生的,因此不能分配给 agent

您需要使 new_parent 继承自 parent,或者您需要删除 agent 上的类型说明符,以便它可以接受任何 Python 对象(例如 object agent).

你不能做的是为一个变量指定一个固定的 Cython 类型,然后希望能够为该变量分配任意类型。