【问题标题】:Will a variable declared with cdef outside a function have the same type inside the function?在函数外部用 cdef 声明的变量在函数内部是否具有相同的类型?
【发布时间】:2013-08-05 11:05:46
【问题描述】:

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

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

【问题讨论】:

    标签: python variables global-variables cython variable-declaration


    【解决方案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

    【讨论】:

    • 谢谢!这个玩具示例与真实代码相差甚远,但我发现不使用global 语句也可以使用全局变量,您尝试过吗?
    • 我接受了你的回答,因为明确使用global 似乎比省略它更快
    • afaik 任何赋值都会为 python 中的赋值变量隐式分配空间。我想,当你省略global 时,这就是发生的事情,因此你最终会再次使用(慢)Python 对象。另一方面,当您只使用它们(无需重新分配)时,当然可以,因为它们在函数范围内也是有效的。
    【解决方案2】:

    我做了以下测试,我相信它可以在外部声明许多函数共享的变量,避免重复代码,无需使用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.]
    

    【讨论】:

      猜你喜欢
      • 2015-02-10
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2019-02-08
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      相关资源
      最近更新 更多