2017-02-06 6 views
4

こんにちは私は対称演算子をPythonでオーバーライドする方法があるのだろうかと思っていました。 Pythonのcommutative operator override

a = A(1) 
a + 1 

しかし、私はしようとした場合::その後、私は行うことができます

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 

:たとえば、のは、私はクラスを持っているとしましょう

1 + a 

私はエラーを取得します。 オペレータを無効にする方法はありますかを追加すると1 + aが機能しますか?

+0

あなたができないことの1つは '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?