Mik*_*ton 8 python metaclass cython
我试图用cython扩充现有的python源代码.pxd,正如Stefan Behnel在"使用Cython编译器编写快速Python代码"的幻灯片32到35中所说明的那样.
作为练习的一部分,我一直__eq__()在用我的元类中的方法撞墙.我希望我能选择一个更简单的案例来启动Cython,但我的生产代码并不那么简单.我编写了一个"最小的,完整的例子"来说明问题...请参阅问题底部的代码.
短篇故事...
cdef inline __richcmp__(Japan_Car_ABC self, Japan_Car_ABC other, int op):,cython会抱怨Special methods must be declared with 'def', not 'cdef'def __richcmp__(Japan_Car_ABC self, Japan_Car_ABC other, int op):,cython会抱怨function definition in pxd file must be declared 'cdef inline'所以cython给了我令人困惑的指导......
问题:
.pxd文件有限制; __richcmp__()我用.pxd一种有效的方式来定义使用a .pxd来增加纯python?.pxd,我该如何解决这个问题才能正确编译?.pxd增加我的纯python元类,而无需在.pyx文件中重写整个元类吗?(例如:class Card在这个项目中)这是我的.pxd......
### File: car_abc.pxd
# cython: infer_types=True
cimport cython
cdef class Japan_Car_ABC:
cpdef public char* model
cpdef public char* color
def __richcmp__(Japan_Car_ABC self, Japan_Car_ABC other, int op):
"""Ref: http://docs.cython.org/src/userguide/special_methods.html#rich-comparisons"""
if op==2:
# op==2 is __eq__() in pure python
if self.model==other.model:
return True
return False
else:
err_msg = "op {0} isn't implemented yet".format(op)
raise NotImplementedError(err_msg)
Run Code Online (Sandbox Code Playgroud)
信息:
car_abc.py:
### File: car_abc.py
from abc import ABCMeta
class Japan_Car_ABC(object):
__metaclass__ = ABCMeta
def __init__(self, model="", color=""):
self.model = model
self.color = color
def __eq__(self, other):
if self.model==other.model:
return True
return False
def __hash__(self):
return hash(self.model)
Run Code Online (Sandbox Code Playgroud)
car.py:
from car_abc import Japan_Car_ABC
class Lexus(Japan_Car_ABC):
def __init__(self, *args, **kwargs):
bling = kwargs.pop("bling", True) # bling keyword (default: True)
super(Lexus, self).__init__(*args, **kwargs)
self.bling = bling
class Toyota(Japan_Car_ABC):
def __init__(self, *args, **kwargs):
super(Toyota, self).__init__(*args, **kwargs)
if __name__=="__main__":
gloria_car = Lexus(model="ES350", color="White")
jeff_car = Toyota(model="Camry", color="Silver")
print("gloria_car.model: {0}".format(gloria_car.model))
print("jeff_car.model: {0}".format(jeff_car.model))
print("gloria_car==jeff_car: {0}".format(gloria_car==jeff_car))
Run Code Online (Sandbox Code Playgroud)
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("car_abc", ["car_abc.py"]),
#Extension("car", ["car.py"]),
]
setup(
name = "really build this thing",
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
Run Code Online (Sandbox Code Playgroud)
简单的答案(从Nils Bruin通过收到cython-users)是pxd不能用于实现方法(例如__richcmp__())。由于我使用的是元类,因此需要将我的代码移植到.pyx中,以便实现__richcmp__()和其他特殊的cython方法。
| 归档时间: |
|
| 查看次数: |
1037 次 |
| 最近记录: |