を持っていますと、extension typeを定義することです。 Pythonは、人々が彼らと彼らの種類を変更することができますので、あなたが、通常class
内のインスタンスの種類属性を課さないでき
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef double var1
cdef np.ndarray[double, ndim=1] Redges
def __init__(self, np.ndarray[double, ndim=1] Redges):
self.Redges = Redges
注:特に、あなたのコードは次のようになります。通常のPythonクラスでクラスレベルにcdef
を入れようとすると、Cythonによってコンパイラエラーが発生します。上記のコードをコンパイルする
は、次のエラーが発生します。
今
Error compiling Cython file:
------------------------------------------------------------
...
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef double var1
cdef np.ndarray[double, ndim=1] Redges
^
------------------------------------------------------------
test_cython.pyx:6:36: Buffer types only allowed as function local variables
、これはない構文エラーです。構文は問題ありません。問題は、単純ににのインスタンス属性がnp.ndarray
であることができないということです。これはcythonの制限です。実際には、あなたは、ファイルが正しくコンパイルされcdef np.ndarray[double, ndim=1] Redges
行をコメントとします
コード:
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef double var1
#cdef np.ndarray[double, ndim=1] Redges
def __init__(self, np.ndarray[double, ndim=1] Redges):
self.Redges = Redges
出力:
$cython test_cython.pyx
$
注:正常にコンパイルされたファイルを意味cython
から出力なし。
この制限は、セクションAttributesで、私は上記のリンク先のドキュメントで説明されています。
Attributes of an extension type are stored directly in the object’s C struct
. [omissis]
Note: You can only expose simple C types, such as ints, floats, and strings, for Python access. You can also expose Python-valued attributes.
属性がstruct
のメンバーであるので、あなただけシンプル Cデータ・タイプを公開することができるという事実であります。 np.ndarray
のようなバッファを許可するには、可変サイズstruct
が必要です。
あなたがタイプnp.ndarray
のインスタンスの属性をしたい場合は、あなたができる最善のobject
のジェネリック型と属性を定義し、それに配列を割り当てることです:
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef double var1
cdef object Redges
def __init__(self, np.ndarray[double, ndim=1] Redges):
self.Redges = Redges
しかし今、毎回あなたがself.Redges
あなたにアクセスcythonの速度を失う。何度でもアクセスすると、正しいタイプのローカル変数に割り当てることができます。 は、ここで私が何を意味するかです:
このように
import numpy as np
cimport numpy as np
cdef class MyClass:
cdef double var1
cdef object Redges
def __init__(self, np.ndarray[double, ndim=1] Redges):
self.Redges = Redges
def do_stuff(self):
cdef np.ndarray[double, ndim=1] ar
ar = self.Redges
ar[0] += 1
return ar[0]
あなたがar
を使用してcythonのすべての速度を持つことができdo_stuff
関数内。
トレースバックを追加 –
これは完全なトレースバックではありません。 – Bakuriu