How to pass subclass in function with base class typehint [duplicate]

狂风中的少年 提交于 2021-02-11 12:18:23

问题


I have a base class A from what I inherit in sub class B. I have a function where an argument has this base class A as typehint. Now I want to pass to this function sub class B. This works, but I get a warning in my IDE "Expected type A, got B instead".

How to do that correctly?

class A: pass

class B(A): pass

def test(a: A): pass

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

EDIT:

I found the issue. I accidentally used the wrong base class as typehint in the test(a: WRONG).

The code above works!

Thanks all for your answers!


回答1:


The hinting a: A means that a is an instance of A (or of its subclasses).

test(B) passes the class B to test, not an instance.

If you pass an instance test(B()) the warning goes away.

If you actually meant for test to accept the class itself, you have to use a tad more advanced hinting:

from typing import Type

class A:
    pass

class B(A):
    pass

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

test(B)


来源:https://stackoverflow.com/questions/61310950/how-to-pass-subclass-in-function-with-base-class-typehint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!