2011-08-08 4 views
2

__cinit__ 또는 __add__에 과부하가 걸릴 수 있습니까? 이 같은 뭔가 :Cython 오버로드 특수 메서드?

cdef class Vector(Base): 
    cdef double x, y, z 

    def __cinit__(self, double all): 
     self.x = self.y = self.z = all 

    def __cinit__(self, double x, double y, double z): 
     self.x = x 
     self.y = y 
     self.z = z 

    def __str__(self): 
     return "Vector(%s, %s, %s)" % (self.x, self.y, self.z) 

    def __add__(self, Vector other): 
     return Vector(
      self.x + other.x, 
      self.y + other.y, 
      self.z + other.z, 
     ) 

    def __add__(self, object other): 
     other = <double>other 
     return Vector(
      self.x + other.x, 
      self.y + other.y, 
      self.z + other.z, 
     ) 

Vector(0) + Vector(2, 4, 7) 호출은 오버로드 된 방법으로 인식되지 __add__(self, Vector other) 것 같아 있도록 플로트가 여기에 필요하다는 것을 알려줍니다. 특별한 방법이 cdef로 정의하지 않아야 만 cdef -fed 기능에 과부하가 될 수 있기 때문에

이 있습니까?

답변

3

특수 함수의 연산자 오버로드가 cython에서 지원되지 않는다고 생각합니다.

가장 좋은 방법은 수동으로 형식 검사 논리를 만들고 그에 따라 파이썬 개체를 캐스팅하는 것입니다.

def __add__(self, other): 
    if type(other) is float: 
     return self.__add__(<double> other) 
    elif isinstance(other,Vector): 
     return self.__add__(<Vector> other) 
    ... 
관련 문제