1

我在同一个模块的所有功能,使用许多变量与同类型:在函数外部用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 

回答

1

原则,用Cython处理全局变量作为Python做,不管无论是C还是Python类型。看看this part of the FAQ

所以,你的(第二)的例子是不行的,你必须在你的函数的使用开始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 

然而,在这一点上我想问题,无论是你真的需要这样做。一般来说,有很好的理由,为什么global variables are bad。所以你可能想重新考虑。

我假设你的三个双打只是一个玩具的例子,所以我不确定你的实际用例是什么。从你的(第一)例子来看,重用代码可以改为由另一个参数扩展功能,像这样做:

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 

这至少会涵盖你的例子func1func2这里分别用y = 0y = 1

+0

谢谢!这个玩具的例子远没有真正的代码,但我发现,使用全局变量可以在不使用'global'语句的情况下完成,你试过了吗? –

+0

我接受了你的答案,因为明确使用'global'似乎比省略它更快 –

+0

afaik任何赋值都为python中的赋值变量隐式分配空间。我想,这就是发生了什么,当你省略'global'时,因此你最终会再次使用(慢)Python对象。另一方面,当你只是使用它们(没有重新分配)当然可行,因为它们在功能范围内也是有效的。 – aepsil0n

0

我提出了以下测试,相信它的工作原理声明由外部许多功能共享的变量,从而避免重复的代码,而无需指定与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.] 
相关问题