问题
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