【问题标题】:How to pass subclass in function with base class typehint [duplicate]如何使用基类类型提示在函数中传递子类[重复]
【发布时间】:2020-08-02 06:37:33
【问题描述】:

我有一个基类A,来自我在子类B 中继承的。 我有一个函数,其中一个参数有这个基类A 作为类型提示。 现在我想传递给这个函数子类B。 这可行,但我在 IDE 中收到警告“预期类型 A,得到 B”。

如何正确地做到这一点?

class A: pass

class B(A): pass

def test(a: A): pass

test(B()) # <- expected type A, got B instead

编辑:

我发现了问题。 我不小心在test(a: WRONG) 中使用了错误的基类作为类型提示。

上面的代码有效!

感谢大家的回答!

【问题讨论】:

  • 你用的是什么IDE?
  • @DeepSpace 感谢您的回复。我也在使用 PyCharm 2020.1

标签: python inheritance


【解决方案1】:

提示a: A 表示aA(或其子类)的实例

test(B) 通过 B 进行测试,而不是实例

如果你传递了一个实例test(B()),警告就会消失。

如果你真的想让test 接受类本身,你必须使用更高级的提示:

from typing import Type

class A:
    pass

class B(A):
    pass

def test(a: Type[A]): pass  # <- no warning here

test(B)

【讨论】:

  • 击败我到Type[A] 答案! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 2017-10-05
  • 2016-10-16
  • 2020-11-21
相关资源
最近更新 更多