函数外用cdef声明的变量在函数内是否具有相同的类型



我在同一模块的所有函数中使用了许多类型相同的变量:

def func1(double x):
    cdef double a,b,c
    a = x
    b = x**2
    c = x**3
    return a+b+c
def func2(double x):
    cdef double a,b,c
    a = x+1
    b = (x+1)**2
    c = (x+1)**3
    return a+b+c

我的问题是,如果我这样做,会是一样的吗?变量声明放在函数之外?(实际情况不同,有2个以上的功能)

cdef double a,b,c
def func1(double x):
    a = x+2
    b = (x+2)**2
    c = (x+2)**3
    return a+b+c
def func2(double x):
    a = x+2
    b = (x+2)**2
    c = (x+2)**3
    return a+b+c

原则上,无论是C类型还是python类型,cython都像python一样处理全局变量。看看常见问题解答的这一部分。

因此,您的(第二个)示例不起作用,您必须在函数开始时使用global variable,如下所示:

def func2(double x):
    global a, b, c
    a = x + 2
    b = (x + 2) ** 2
    c = (x + 2) ** 3
    return a + b + c

然而,在这一点上,我想问一下,你是否真的需要这样做。一般来说,有很好的论据可以解释为什么全局变量是坏的。所以你可能真的想重新考虑一下。

我认为,你的三个替身只是一个玩具示例,所以我不确定你的实际用例是什么。从你的(第一个)示例来看,重用代码可以通过用另一个参数扩展函数来实现,比如:

def func(double x, double y=0):
    cdef double a, b, c
    a = x + y
    b = (x + y) ** 2
    c = (x + y) ** 3
    return a + b + c

这至少可以通过分别使用y = 0y = 1来覆盖您的示例func1func2

我进行了以下测试,我相信它可以声明外部许多函数共享的变量,避免重复代码,而无需使用global进行指定。

_test.pyx文件中:

import numpy as np
cimport numpy as np
cdef np.ndarray a=np.ones(10, dtype=FLOAT)
cdef np.ndarray b=np.ones(10, dtype=FLOAT)
cdef double c=2.
cdef int d=5
def test1(double x):
    print type(a), type(b), type(c), type(d)
    print a + c*b + 1*c*x + d
def test2(double x):
    print type(a), type(b), type(c), type(d)
    print a + c*b + 2*c*x + d

test.py文件中:

import pyximport; pyximport.install()
import _test
_test.test1(10.)
_test.test2(10.)

给出:

<type 'numpy.ndarray'> <type 'numpy.ndarray'> <type 'float'> <type 'int'>
[ 28.  28.  28.  28.  28.  28.  28.  28.  28.  28.]
<type 'numpy.ndarray'> <type 'numpy.ndarray'> <type 'float'> <type 'int'>
[ 48.  48.  48.  48.  48.  48.  48.  48.  48.  48.]

最新更新