Skip to content Skip to sidebar Skip to footer

How To Pass Subclass In Function With Base Class Typehint

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. Th

Solution 1:

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

test(B) passes the classB 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 importTypeclassA:
    passclassB(A):
    passdeftest(a: Type[A]): pass# <- no warning here

test(B)

Post a Comment for "How To Pass Subclass In Function With Base Class Typehint"