【问题标题】:Importing cython Extension Class into python file (positional argument将cython扩展类导入python文件(位置参数
【发布时间】:2017-04-05 15:15:35
【问题描述】:

我有两个文件:一个 run.py 和一个 constraints.pyx。我想在约束.pyx 中的this code 中创建一个类似于L1Penalty 的扩展类,并在run.py 中实例化它以在函数中使用。

我做了什么:

constraints.pyx 包含一个扩展类,this code 中 Penalty 类的子类:

from lightning.impl.sag_fast cimport Penalty

cdef class ProbaPenalty(Penalty):
    def __cinit__(self):
        self.support_lagged = False
...

在 run.py 中,我创建了一个 ProbaPenalty 实例:

import pyximport; pyximport.install()
from constraints import ProbaPenalty
pen = ProbaPenalty()

我的错误是:

cinit() 正好采用 1 个位置参数(给定 0)

有没有粗心的错误?我在stackoverflow上找不到类似的问题。 我试着改变我的 cinit 来接受一个 bint support_lagged 这样我现在就有了

cdef class ProbaPenalty(Penalty):
    def __cinit__(self, bint support_lagged):
        self.support_lagged = support_lagged

然后使用

pen = ProbaPenalty(0)

这一次,我得到了错误:

AttributeError: 'custom_constraints.ProbaPenalty' 对象没有属性 'b'

我在哪里称呼 b,b 又是从哪里来的?

一开始,我希望 ProbaPenalty 有一个双精度向量 b,我做了 cinit(self, double* b),但后来我更改了代码,删除了 .c 和 .so 文件等,查看当前的 .c 文件,也没有属性 b 。

我也尝试使用 setup.py 进行编译,但遇到了同样的问题。

【问题讨论】:

  • 根据我投票结束的答案下的 OP 评论,因为“无法再复制”

标签: python cython


【解决方案1】:

__cinit__ 方法不适合 Python 级访问扩展类型,见http://docs.cython.org/en/latest/src/reference/extension_types.html

定义一个 reguar __init__ 以在 Python 中使用。

【讨论】:

  • 实际上,在关闭并重新打开 spyder 之后,我今天早上再次尝试运行我所拥有的东西——它甚至可以使用 cinit。在任何情况下,它都无法解释为什么存在属性 b。我想当我重新运行 setup.py 时,有一些变量没有被清除。
猜你喜欢
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多