python - 重写方法的类型提示传播

标签 python pycharm

是否可以将类型提示传播到重写方法?

假设我有以下类(class):

class Student:
    def study():
        pass

class Option:
    self.option_value

class BaseChoice:
   def make_choice(self, student, options):
        """
        :type student: Student
        :type options: list[Option]
        """

class RationalChoice(BaseChoice):
   def make_choice(self, student, options):
        pass

当我在RationalChoice.make_choice中时,pycharm不建议自动完成options属性/方法,但是它为student选择正确的提示。显而易见的解决方法是仅复制文档字符串,但我将拥有数十个不同的 BaseChoice 后代,因此这是不切实际的。

我使用的是 PyCharm 3.1.1,社区版和专业版都会受到影响。

这是 Python 本身完全缺少的东西,还是 PyCharm 中完全缺少的东西?

最佳答案

PyCharm 在重写方法时不会查看父类(super class)类型提示。我不知道这是一个错误还是一个功能,尽管我倾向于后者:Python 不要求重写方法具有相同的签名或接受与它们重写的方法相同的类型。换句话说,BaseChoice 上的类型提示不会自动对 RationalChoice 有效。

PyCharm 所做的事情(似乎让您感到困惑)是快速猜测并确定 Student 对于名为 student 的参数来说是一个合理的类。没有类 Options,因此启发式失败。

因此,如果您真的非常想要类型提示,那么除了在您想要的任何地方指定它们之外,别无选择。

如果您使用的是 Python 3,您可以尝试新的语言内类型提示(注释)语法:

class RationalChoice(BaseChoice):
    def make_choice(self, student: Student, options: list):
        return

关于python - 重写方法的类型提示传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22388645/

相关文章:

python - PyCharm 5.0.1 不解析内置模块/方法

JetBrains 中的 Python 2 类型代码完成?

python-3.x - Pyinstaller 不会在 Python 虚拟环境中查找文件

python - 使用 Ubuntu 16.04 获取 wxPython 并将其与 Pycharm 一起使用

python - newrelic 代理仅在登台时不向 newrelic 服务器发送数据

python - 如何更新基于其他 Pandas 数据框的系列

python - vscode django调试报错: Couldn't import Django

python - 如何将 Redis 与 SQLAlchemy 集成

python - 两层神经网络 Tensorflow python

python - 为什么 PyCharm 错误地猜测 dict_items 列表的类型?