Subclass in type hinting

后端 未结 1 535
醉酒成梦
醉酒成梦 2020-12-03 06:40

I want to allow type hinting using Python 3 to accept sub classes of a certain class. E.g.:

class A:
    pass

class B(A):
    pass

class C(A):
    pass

de         


        
相关标签:
1条回答
  • 2020-12-03 07:06

    When you specify cls: A, you're saying that cls expects an instance of type A. The type hint to specify cls as a class object for the type A (or its subtypes) uses 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).

    0 讨论(0)
提交回复
热议问题