2017-02-06 2 views
4

안녕하세요 Python에서 대칭 연산자를 재정의하는 방법이 있는지 궁금합니다. Python commutative operator override

class A: 
    def __init__(self, value): 
     self.value = value 

    def __add__(self, other): 
     if isinstance(other, self.__class__): 
      return self.value + other.value 
     else: 
      return self.value + other 

그럼 내가 할 수있는 :

a = A(1) 
a + 1 

을하지만 시도하는 경우 : 예를 들어, 내가 클래스가 있다고 가정 해 보자

1 + a 

나는 오류가 발생합니다. 연산자를 무시하는 방법이 있습니까 을 추가하면 1 + a가 작동합니까?

+0

당신이 할 수없는 것은'int .__ add__ = something'입니다. 이것은 읽기 전용입니다. –

+0

이것은 int의 add 연산자를 재정의하는 방법입니다. 나는 그것을하고 싶지 않다. 내 수업 만 확장하고 싶습니다. –

답변

3

클래스에 __radd__ 메소드를 구현하기 만하면됩니다. int 클래스가 추가를 처리 할 수 ​​없으면 구현 된 경우 __radd__이 처리됩니다. 예를 들어

class A(object): 
    def __init__(self, value): 
     self.value = value 

    def __add__(self, other): 
     if isinstance(other, self.__class__): 
      return self.value + other.value 
     else: 
      return self.value + other 

    def __radd__(self, other): 
     return self.__add__(other) 


a = A(1) 
print a + 1 
# 2 
print 1 + a 
# 2 

는, 표현 X 평가 - Y는 __rsub__() 방법이있는 클래스의 인스턴스 이다 Y를, y.__rsub__(x)가 호출됩니다 x.__sub__(y) 반환 NotImplemented 경우.

동일 내용은 x + y에 적용됩니다.

참고로, 클래스를 object으로 서브 클래 싱하려는 것이 좋습니다. What is the purpose of subclassing the class "object" in Python?