简体   繁体   English

输入提示这是一个子类

[英]Type Hint that this is a Subclass

How does one indicate via type hints that one class is a subclass of another?如何通过类型提示表明一个类是另一个类的子类? Eg.例如。

class Foo:
  def foo(self, x):
    pass

def dynamic() -> Type[Foo]:
  class SubFoo(Foo):
    pass

  return SubFoo

class SubSubFoo(dynamic()):
  def f|  # no suggestions from my editor

My editor (PyCharm) does not provide suggestions in the above case, indicating that static analysis does not recognize that SubSubFoo is a subtype of Foo .我的编辑器(PyCharm)在上述情况下没有提供建议,说明静态分析无法识别SubSubFooFoo的子类型。 How can I use type hints to indicate this?如何使用类型提示来表明这一点?

I have an answer from JetBrains indicating that this is a limitation of PyCharm rather than a limitation or misuse of type hints:我从 JetBrains 得到了一个答案,表明这是 PyCharm 的限制,而不是类型提示的限制或误用:

In this particular case it's IDE limitation, we don't look inside dynamic() function as it may be a lot more complex.在这种特殊情况下,这是 IDE 的限制,我们不会查看 dynamic() 函数的内部,因为它可能要复杂得多。

- Andrey Resler - 安德烈雷斯勒

As a fix, I am using an idiom where whenever I subclass dynamic() I will also subclass Foo after that, which leads to the desired suggestions appearing without altering the logic of the program (even if it does look a bit weird).作为修复,我使用了一个习惯用法,每当我将dynamic()子类化时,我也会在此之后将Foo子类化,这会导致在不改变程序逻辑的情况下出现所需的建议(即使它看起来确实有点奇怪)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM