PyCharm类型提示不适用于重载的操作员

问题描述:

这是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在我的所有模块的顶部。任何帮助或建议表示赞赏。

好的,我不能添加评论,因为我的声望太低,但我可以创建一个答案。似乎是合法的。

我试过你代码示例(使用运算符),我没有得到警告。 即使我遗漏了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。 –