覆盖方法的类型提示传播 [英] Type hinting propagation for overriding methods

查看:51
本文介绍了覆盖方法的类型提示传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将类型提示传播到覆盖方法?

Is it possible to propagate type hinting to overridding methods?

比如说,我有以下课程:

Say, I have the following classes:

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 后代,所以这不切实际.

When I'm inside RationalChoice.make_choice pycharm does not suggest autocomplete for options properties/methods, however it picks right hint for student. The obvious workaround would be to just copy the docstring, but I'm going to have tens of different BaseChoice descendants, so it's just not practical.

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

I'm using PyCharm 3.1.1, both Community and Professional versions are affected.

它是 Python 本身完全缺失的东西,还是只是在 PyCharm 中缺失的?

Is it something completely missing in python itself, or just in PyCharm?

推荐答案

PyCharm 在重写方法时不会查看超类类型提示.我不知道这是一个错误还是一个特性,尽管我倾向于后者:Python 不需要覆盖方法与它们覆盖的方法具有相同的签名或接受相同的类型.换句话说,BaseChoice 上的类型提示不会自动对 RationalChoice 有效.

PyCharm does not look at the superclass type hints when overriding methods. I don't know if this is a bug or a feature, although I would be leaning toward the latter: Python does not require overriding methods to have the same signatures or accept the same types as the methods they override. Put differently, type hints on BaseChoice are not automatically valid for RationalChoice.

PyCharm 所做的,并且似乎让您感到困惑的是,快速猜测并确定 Student 将是名为 student 的参数的合理类.没有 Options 类,因此启发式失败.

What PyCharm does do, and what seems to be confusing you, is take a quick guess and decide that Student would be a sensible class for a parameter called student. There is no class Options, so that heuristic fails.

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

So if you really, really want type hints, there's really no alternative to specifying them everywhere you want them.

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

If you are using Python 3, you could try the new in-language type hint (annotation) syntax:

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

这篇关于覆盖方法的类型提示传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆