2016-12-02 6 views
1

는 또한 다른 종류의 작업을 수행하도록 설계 mint클래스 인스턴스가 오른쪽에있을 때 클래스가 추가 작업을 제어하도록하려면 어떻게해야합니까?

class mint(object): 
    def __init__(self, i): 
     self.i = i 

    def __add__(self, other): 
     o = other.i if isinstance(other, mint) else other 
     return mint(1 + self.i + o) 

    def __repr__(self): 
     return str(self.i) 

내 수업 고려하십시오.

a = mint(1) 

a + 1 + 2 

6 

그러나 내 개체가 오른쪽에있는 동안 추가하는 기능이 작동하지 않습니다.

1 + a 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-519-8da568c0620a> in <module>() 
----> 1 1 + a 
TypeError: unsupported operand type(s) for +: 'int' and 'mint' 

질문 : 어떻게 1 + a이 작동하도록 내 클래스를 수정합니까?

+1

http://stackoverflow.com/a/5082229/6394138 – Leon

+1

뿐만 아니라 또한 ['.__ iadd__'] 구현 고려 아래와 같이 ('.__ radd__' 구현 https://docs.python.org/3.5/reference/datamodel.html#object.__iadd__). –

+0

'pandas '밖에는 모험심이 들었다. –

답변

1

당신은 __radd__ 사용할 수 있습니다

class mint(object): 
    def __init__(self, i): 
     self.i = i 

    def __add__(self, other): 
     o = other.i if isinstance(other, mint) else other 
     return mint(1 + self.i + o) 

    def __repr__(self): 
     return str(self.i) 

    def __radd__(self, other): 
     return self + other 

a = mint(1) 
print(1 + a) 

출력 :

3 

여기 파이썬 문서에서 설명이있다 :

이 방법은 (이진 산술 연산을 구현하기 위해 호출되는

+, -, *, @, /, //, %, divmod(), pow(), **, < <, >>, &, ^, |) 반영된 (스왑 된) 피연산자. 이 함수는 왼쪽 피연산자가 해당 연산을 지원하지 않고 피연산자가 다른 유형 인 경우에만 호출됩니다. [2] 예를 들어, x - y 표현식을 평가하려면 y는 rsub() 메소드가있는 클래스의 인스턴스입니다 (예 : y). rsub (x)는 x 인 경우 호출됩니다. 하위 (y)은 NotImplemented를 반환합니다.

1

구현 __radd__

In [1]: class mint(object): 
    ...:  def __init__(self, i): 
    ...:   self.i = i 
    ...: 
    ...:  def __add__(self, other): 
    ...:   o = other.i if isinstance(other, mint) else other 
    ...:   return mint(1 + self.i + o) 
    ...: 
    ...:  def __repr__(self): 
    ...:   return str(self.i) 
    ...:   
    ...:  def __radd__(self, other): 
    ...:   return self.__add__(other) 
    ...:  

In [2]: a = mint(1) 

In [3]: 1 + a 
Out[3]: 3 
관련 문제