2015-10-19 26 views
0

這是this thread中提到的那種,但從未解決。PyCharm類型提示不適用於重載的操作員

我有一個載體類:

class Vector2D(object): 

    # ... 

    def __add__(self, other): 
     return Vector2D(self.x + other.x, self.y + other.y) 

    # ... 

    def __truediv__(self, scalar): 
     return Vector2D(self.x/scalar, self.y/scalar) 

然後,我有一個函數,它的類型是暗示接受的Vector2D:

def foo(vector): 
    """ 
    :type vector: Vector2D 
    """ 
    print("<{}, {}>".format(vector.x, vector.y)) 

如果我嘗試調用foo像這樣,我得到一個奇怪的警告說"Expected type 'Vector2D', got 'int' instead"

foo((Vector2D(1, 2) + Vector2D(2, 3))/2) 

然而,它工作正常w母雞我運行它,並沒有任何警告,當我明確地使用的Vector2d方法:

foo(Vector2D(1, 2).__add__(Vector2D(2, 3)).__truediv__(2)) 

請注意:我使用Python 2.7,但我有from __future__ import division, print_function在我的所有模塊的頂部。任何幫助或建議表示讚賞。

回答

0

好的,我不能添加評論,因爲我的聲望太低,但我可以創建一個答案。似乎是合法的。

我試過你代碼示例(使用運算符),我沒有得到警告。 即使我遺漏了from __future__ import division, print_function。 另外,如__rmul__的正確操作數(或他們稱爲?)不會產生警告。事實上,自動完成的作品,太

(2 * Vector2D(0, 0)) 

我可以按.和它讓我看到Vector2D類的屬性。

我有PyCharm 4.5.4專業版。

但是,您可以嘗試手動指定的經營者的返回類型:

def __add__(self, other): 
    """ 
    :rtype: Vector2D 
    """ 
    return ... 

您也可以嘗試清除PyCharm-緩存:File -> Invalidate Caches/Restart... -> Invalidate and Restart

+0

我使用PyCharm 4.5.4社區版,所以這可能與它有關。我嘗試了其他解決方案,但它們不適合我。我想這只是升級的另一個原因:D。 –

相關問題