问题:用户定义类的类型提示

似乎找不到确切的答案。我想为一个函数提供类型提示,该类型是我定义的一些自定义类,称为它CustomClass()

然后让我们说在某个函数中调用它FuncA(arg),我有一个名为的参数arg。键入提示的正确方法FuncA是:

def FuncA(arg: CustomClass):

或者是:

def FuncA(Arg:Type[CustomClass]):

Couldn’t seem to find a definitive answer. I want to do a type hint for a function and the type being some custom class that I have defined, called it CustomClass().

And then let’s say in some function, call it FuncA(arg), I have one argument named arg. Would the correct way to type hint FuncA be:

def FuncA(arg: CustomClass):

Or would it be:

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]'

The former is correct, if arg accepts an instance of CustomClass:

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass

In case you want the class CustomClass itself (or a subtype), then you should write:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself

Like it is written in the documentation about Typing:

class typing.Type(Generic[CT_co])

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C.

The documentation includes an example with the int class:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。