Cython:如何创建一个接收不同类型参数的构造函数?

问题描述 投票:0回答:1

所以我有这个 Point 类。所以我希望它能够接收

double
SomeType
参数。

[点.pxd]

from libcpp.memory cimport shared_ptr, weak_ptr, make_shared
from SomeType cimport _SomeType, SomeType

cdef extern from "Point.h":
    cdef cppclass _Point:
        _Point(shared_ptr[double] x, shared_ptr[double] y)
        _Point(shared_ptr[double] x, shared_ptr[double] y, shared_ptr[double] z)
        _Point(shared_ptr[_SomeType] x, shared_ptr[_SomeType] y)
        _Point(shared_ptr[_SomeType] x, shared_ptr[_SomeType] y, shared_ptr[_SomeType] z)

        shared_ptr[_SomeType] get_x()
        shared_ptr[_SomeType] get_y()
        shared_ptr[_SomeType] get_z()


cdef class Point:
    cdef shared_ptr[_Point] c_point

[点.pyx]

from Point cimport *

cdef class Point:
    def __cinit__(self, SomeType x=SomeType("0", None), SomeType y=SomeType("0", None), SomeType z=SomeType("0", None)):
        self.c_point = make_shared[_Point](x.thisptr, y.thisptr, z.thisptr)

    def __dealloc(self):
        self.c_point.reset()

    def get_x(self) -> SomeType:
        cdef shared_ptr[_SomeType] result = self.c_point.get().get_x()
        cdef SomeType coord = SomeType("", None, make_with_pointer = True)
        coord.thisptr = result
        return coord

    def get_y(self) -> SomeType:
        cdef shared_ptr[_SomeType] result = self.c_point.get().get_y()
        cdef SomeType coord = SomeType("", None, make_with_pointer = True)
        coord.thisptr = result
        return coord

    def get_z(self) -> SomeType:
        cdef shared_ptr[_SomeType] result = self.c_point.get().get_z()
        cdef SomeType coord = SomeType("", None, make_with_pointer = True)
        coord.thisptr = result
        return coord

    property x:
        def __get__(self):
            return self.get_x()

    property y:
        def __get__(self):
            return self.get_y()

    property z:
        def __get__(self):
            return self.get_z()

我应该如何编写 .pxd 和 .pyx 文件,以便我的 Point 构造函数可以接收不同类型的参数? 我非常感谢您的帮助。

python cython cythonize
1个回答
0
投票

您可以将

__cinit__
参数类型定义为
object
。然后使用
isinstance
函数来确定参数类型:

from Point cimport *

cdef class Point:

    def __cinit__(self, object x=None, object y=None, object z=None):
        cdef shared_ptr[_Point] point

        if isinstance(x, (int, float)):  # Check for numeric types (double)
            point = make_shared[_Point](make_shared[double](x), make_shared[double](y))
        else:
            point = make_shared[_Point](x.thisptr, y.thisptr, z.thisptr)  # Use SomeType

        self.c_point = point
© www.soinside.com 2019 - 2024. All rights reserved.