我有一個純Python模塊a.py
文件,其中包含與用Cython增強類:用Cython:每股純Python模塊
@cython.cclass
class Test
我如何使用這個類在其他純Python模塊b.py
?我試圖from a import Test
但隨後用Cython編譯器告訴我Not a type
無論我在b.py
我有一個純Python模塊a.py
文件,其中包含與用Cython增強類:用Cython:每股純Python模塊
@cython.cclass
class Test
我如何使用這個類在其他純Python模塊b.py
?我試圖from a import Test
但隨後用Cython編譯器告訴我Not a type
無論我在b.py
在評論中使用Test
就像我說的,你可以做到這一點通過使用除了.py
文件.pxd
文件中指定的類型。我知道這並不像將所有內容放在.py
文件中那樣優雅,但據我所知,這是你能做的最好的。
a.py:
class Test:
pass
a.pxd:
cdef class Test:
pass
b.py:
# here I use Test in all the places I think you could want to use it:
# as a function argument
# as a variable in a function
# in a class
import a
def f(x):
return x
def g():
t = a.Test()
return t
class C:
pass
b.pxd:
import cython
cimport a
cpdef f(a.Test x)
@cython.locals(t=a.Test)
cpdef g()
cdef class C:
cdef a.Test t
您可以通過檢查生成的b.c
文件來驗證它是否正確使用類型信息。
僅供參考,相關文件是http://docs.cython.org/src/tutorial/pure.html#magic-attributes-within-the-pxd
作品!我從來沒有想過爲'b.py'創建一個pxd文件 – dominicp
我懷疑你必須創建一個.pxd定義文件既'a.py'和'b.py'並定義類型存在。不幸的是,它涉及在兩個地方複製信息,但它並沒有打破從普通Python使用'a.py'和'.b.py'的能力。 – DavidW
我試過了,但是然後cython編譯不再工作。因爲你不能在'.py'文件中使用'cimport'來共享定義文件 – dominicp
如果你正在定義一個函數參數的類型,你可以把cimport放在b.pxd文件中。如果你在一個函數中定義了一個類型,我不認爲你可以(在這種情況下,我不知道!) – DavidW