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.] 
相關問題