2014-02-11 43 views
7

元組表示分數。我想由recipricalPython類__div__問題

class Test(): 
    def __init__(self): 
     self._x=(1,2) 
    def __div__(self,div_fraction): 
     return (self._x[0]*div_fraction[1],self._x[1]*div_fraction[0]) 

y=Test() 
z=y/(1,3) 
print(z) 

相乘來劃分分數給我:

Traceback (most recent call last): 
    File "E:/test.py", line 8, in <module> 
    z=y/(1,3) 
TypeError: unsupported operand type(s) for /: 'Test' and 'tuple' 

然而,當我改變__div____mul__和使用*代替/它做什麼,它應該。

如何解決我收到的異常?

+0

'y'的類型是Test'的'一個對象,你會期望能夠將一個對象與元組的結果呢? – alfasin

+1

@alfasin:無論方法如何定義它。 –

+0

是的,我意識到,但不應該遵循我的__div__方法,我將它從__init__中的數字?它適用於我使用__mul__。 – user3295426

回答

12

Python 3.x使用__truediv____floordiv____div__是2.x-只。

+0

謝謝。這工作。我應該發佈什麼版本的Python。 – user3295426

+0

既不適合我,也不奇怪... – alfasin