【问题标题】:PyCharm type hinting doesn't work with overloaded operatorsPyCharm 类型提示不适用于重载运算符
【发布时间】:2015-10-19 21:06:11
【问题描述】:

这在this thread 中有所提及,但从未解决。

我有一个向量类:

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)

但是,我运行时它运行良好,并且当我显式使用Vector2d的方法时没有警告:

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

请注意,我使用的是 Python 2.7,但我在所有模块的顶部都有 from __future__ import division, print_function。任何帮助或建议表示赞赏。

【问题讨论】:

    标签: python python-2.7 operator-overloading pycharm


    【解决方案1】:

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

    我尝试了您的代码示例(使用运算符),但没有收到警告。 即使我遗漏了from __future__ import division, print_function。 像__rmul__ 这样的正确操作数(或者它们叫什么?)也不会产生警告。事实上,自动完成功能也有效

    (2 * Vector2D(0, 0))
    

    我可以按.,它会显示Vector2D 类的属性。

    我有 PyCharm 4.5.4 Professional。

    但是,您可以尝试在运算符中手动指定返回类型:

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

    您也可以尝试清除 PyCharm-Cache:File -&gt; Invalidate Caches/Restart... -&gt; Invalidate and Restart

    【讨论】:

    • 我使用的是 PyCharm 4.5.4 社区版,所以这可能与它有关。我尝试了您的其他解决方案,但它们对我不起作用。我想这只是升级的另一个原因:D。
    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2018-07-09
    相关资源
    最近更新 更多