![](/img/trans.png)
[英]How to Manipulate Variable Value inside a Function When The Variable was Declared Outside the Function?
[英]Will a variable declared with cdef outside a function have the same type inside the function?
我在同一模块的所有函数中使用许多具有相同类型的变量:
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
我的问题是,如果我按如下所示进行操作,会不会一样? 将变量声明放置在函数外部? (实际情况有所不同,并且具有两个以上的功能)
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一样处理全局变量。 看看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
但是,在这一点上,我想问一问,您是否真的需要这样做。 通常,有很多好的论据,为什么全局变量是坏的 。 因此,您可能会想重新考虑。
我认为,您的三个双打只是一个玩具示例,所以我不确定您的实际用例是什么。 从您的(第一个)示例来看,可以通过使用另一个参数扩展该函数来重用代码,例如:
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 = 0
和y = 1
至少覆盖您的示例func1
和func2
。
我进行了以下测试,我相信它可以声明外部许多函数共享的变量,从而避免重复代码,而无需使用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.]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.