【问题标题】:Python subclass not properly inheriting cython base class methods [duplicate]Python子类没有正确继承cython基类方法[重复]
【发布时间】:2019-12-17 03:47:17
【问题描述】:

基本上,我在 Cython 中定义了一个基类,其基本结构如下。这是在 baseclass.pyx 文件中。

cdef class BaseClass:
    def __init__(self, fov):
        self.fov = fov

    cdef Vector3 MyMethod(self, parameter):
        cdef Vector3 transformed = Vector3()
        return transformed

我有一个 python 类继承了基本的 cython 类,如下所示:

from baseclass import BaseClass

class Child(BaseClass):
    def __init__(self, near=1e-6, far=1e-6):
        self._near = near
        self._far = far

    # more methods here

最后,我创建了一个子类的实例并尝试调用父类方法:

temp = Child()
temp.MyMethod(parameter)

我得到了错误:

'Child' has no attribute 'MyMethod'.

【问题讨论】:

  • 当您使用__init__ 时,您会覆盖父类。见w3schools.com/python/python_inheritance.asp
  • 所以我将super().__init__(fov) 添加到孩子__init__ (它也将fov 作为参数),但这不起作用。但是,向我通过 super 调用父方法的子方法添加一个方法确实有效。没有更好的方法解决这个问题吗?还尝试将BaseClass.__init__(self, fov) 添加到子构造函数中,但这也不起作用。

标签: python inheritance cython


【解决方案1】:

您需要使用cpdef,如下:

cdef class BaseClass:
    def __init__(self, fov):
        self.fov = fov

    cpdef Vector3 MyMethod(self, parameter):
        cdef Vector3 transformed = Vector3()
        return transformed

cpdef 关键字使 Cython 生成 cdef 函数和 def 函数。后者基本上只是调用前者,但允许您从 Python 调用函数。

【讨论】:

  • 是的,这解决了它。谢谢你。 Cython 新手,很容易错过。
猜你喜欢
  • 2017-11-12
  • 1970-01-01
  • 2012-05-11
  • 2023-03-23
  • 1970-01-01
  • 2018-04-05
  • 2013-11-17
  • 2020-02-09
  • 1970-01-01
相关资源
最近更新 更多