具有用户定义类的类型提示

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

然后我们假设在一个函数中,称为 FuncA(arg),我有一个参数叫做 arg。键入提示 FuncA的正确方式是:

def FuncA(arg: CustomClass):

还是说:

from typing import Type


def FuncA(Arg:Type[CustomClass]):
85209 次浏览

如果 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])

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

Willem Van Onsem 的答案当然是正确的,但我想提供一个小小的更新。在 PEP 585中,在标准集合中引入了类型提示泛型。例如,我们以前必须说。

from typing import Dict


foo: Dict[str, str] = { "bar": "baz" }

我们现在可以放弃 typing模块中的并行类型层次结构,只需说

foo: dict[str, str] = { "bar": "baz" }

这个特性可以在 python 3.9 + 中使用,如果使用 from __future__ import annotations,也可以在3.7 + 中使用。

就这个特定的问题而言,这意味着我们现在可以简单地使用内置的 type对类进行注释,而不是使用 from typing import Type:

def FuncA(arg: type[CustomClass]):