问题:用户定义类的类型提示
似乎找不到确切的答案。我想为一个函数提供类型提示,该类型是我定义的一些自定义类,称为它CustomClass()。
然后让我们说在某个函数中调用它FuncA(arg),我有一个名为的参数arg。键入提示的正确方法FuncA是:
def FuncA(arg: CustomClass):
或者是:
def FuncA(Arg:Type[CustomClass]):?
回答 0
该前者是正确的,如果arg接受一个实例CustomClass:
def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass如果您想要类CustomClass本身(或子类型),则应编写:
from typing import Type  # you have to import Type
def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself就像在有关打字的文档中写的那样:
class typing.Type(Generic[CT_co])带注释的变量
C可以接受type的值C。相反,带注释Type[C]的变量可以接受本身是类的值 -具体地说,它将接受的类对象C。
该文档包含有关int该类的示例:
a = 3 # Has type 'int' b = int # Has type 'Type[int]' c = type(a) # Also has type 'Type[int]'
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

