Subclass in type hinting

拈花ヽ惹草 提交于 2019-11-29 09:14:39
Ashwini Chaudhary

When you do cls: A, you're saying that cls is going to an instance of type A. To make it work with type or its subtypes use typing.Type.

from typing import Type
def process_any_subclass_type_of_A(cls: Type[A]):
    pass

From The type of class objects :

Sometimes you want to talk about class objects that inherit from a given class. This can be spelled as Type[C] where C is a class. In other words, when C is the name of a class, using C to annotate an argument declares that the argument is an instance of C (or of a subclass of C), but using Type[C] as an argument annotation declares that the argument is a class object deriving from C (or C itself).

I found the soluton. Use:

from typing import Type
def process_any_subclass_type_of_A(cls: Type[A]):
    pass

And the desired behavior will be there as noted in the PEP above.

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