gpt4 book ai didi

python - 带有 Cython 装饰器的纯 Python : How to get attribute access at module level

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:06 24 4
gpt4 key购买 nike

我想用 Cython 装饰器编写一些纯 Python,但是当我将我的 NONE.PY 重命名为 NONE.PYX 时,我遇到了一个错误。为了解决这个问题,我需要用一个没有装饰器的纯 python 定义调用来包装每个属性。我想知道为什么...

这里是模块none.pyx(如果重命名为none.py,就完全没有问题)

import cython

@cython.cfunc
@cython.returns(cython.double)
@cython.locals(n=cython.int,i=cython.int,r=cython.int)
def ccrange(n):
r=0
for i in range(n):
r+=i
return r

def crange(n): return ccrange(n)

和 python 测试文件 test_none.py:

import pyximport; pyximport.install()
import none
n=10000
print ">>pure python call>>",none.crange(n)
print ">>cython call>>",none.ccrange(n)

none.pyx 的结果:

pure python call>> 49995000.0 cython call>> Traceback (most recent call last): File "C:\Users\damien\python4d\bacoland\test_none.py", line 6, in print ">>cython call>>",none.ccrange(n)
AttributeError: 'module' object has no attribute 'ccrange'

将 none.pyx 重命名为 none.py,给出:

pure python call>> 49995000 cython call>> 49995000

感谢帮助!祝你有个美好的一天:-)

编辑:避免装饰器@cython.cfunc 打破了 cython 的速度优势......考虑以下使用和不使用 @cython.cfunc 的代码:

@cython.cfunc
@cython.returns(cython.double)
@cython.locals(n=cython.int)
def fibo_c(n):
if n == 0 or n == 1:
return n
return fibo_c(n-2) + fibo_c(n-1)

最佳答案

@cython.cfunc 装饰器等同于 cdef 函数(详见 here),因此该函数只能在 C 中访问代码。因此,要使其可从 Python 访问,请删除 @cython.cfunc

关于python - 带有 Cython 装饰器的纯 Python : How to get attribute access at module level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com