2016-08-18 51 views
1

我試圖在這個例子中超載運營__mul__蟒蛇

class foo: 
    def __init__(self, data): 
     self.data = data 
    def __mul__(self, other): 
     if type(other) in (int, float): 
      return foo(self.data * other) 
     else: 
      return foo(self.data * other.data) 

if __name__ == '__main__': 
    f1 = foo(10) 
    f2 = foo(20) 

    (f1*f2).data # 200 
    (f1*50).data # 500 
    (50*f1).data # TypeError: unsupported operand type(s) for *: 'int' and 'instance' 

但是它並沒有在50 * f1工作落實__mul__

有誰知道如何解決它?

回答

3

爲此,您需要__rmul__方法:

這些方法稱爲執行二進制算術運算(+, - ,*,/,%,divmod(),POW(),**, < <,>>,&,^,|)與反射(交換)操作數。

你的情況:

class foo: 
    def __init__(self, data): 
     self.data = data 

    def __mul__(self, other): 
     # As before 

    def __rmul__(self, other): 
     # This will be called in the situation you brought up. 
+0

在這種情況下,它是很容易只需添加'__rmul__ = __mul__'類定義('後__mul__'當然:-) – mgilson

+0

@mgilson這是一個優點 - 非常感謝。 (我必須承認,我沒有想到實現,只是如何獲得所謂的方法)。 –