gpt4 book ai didi

python - PyCharm 类型提示不适用于重载运算符

转载 作者:行者123 更新时间:2023-12-05 07:52:48 25 4
gpt4 key购买 nike

这在 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。感谢任何帮助或建议。

最佳答案

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

我尝试了您的代码示例(使用运算符),但没有收到警告。即使我遗漏了 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 缓存:File -> Invalidate Caches/Restart... -> Invalidate and Restart

关于python - PyCharm 类型提示不适用于重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33223910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com