Cython元类.pxd:我应该如何实现`__eq__()`?

2024-06-09 14:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用cython .pxd来扩充现有的python源代码,如Stefan Behnel在"Using the Cython Compiler to write fast Python code"的幻灯片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给了我混乱的指导。。。在

问题

  • 我知道纯python .pxd文件有限制;在我的.pxd中定义{}是使用.pxd来扩充纯python的有效方法吗?在
  • 如果这是使用.pxd的有效方法,我如何修复它以正确编译?在
  • 如果这是错误的,.pxd可以扩充我的纯python元类,而不需要在.pyx文件中重新编写整个元类吗?(示例:^{} in this project

这是我的.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)

信息性

汽车_abc.py公司公司名称:

^{pr2}$

在汽车.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))

在设置.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
)

Tags: pyselfmodeldefcarextcythonkwargs