用户定义类的类型提示


103

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

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

def FuncA(arg: CustomClass):

或者是:

def FuncA(Arg:Type[CustomClass]):

Answers:


125

前者是正确的,如果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]'

1
Type来自py3.6及更高版本?我刚得到一个NameError
cs95

3
请注意,如果您在同一文件中拥有该类,则在评估类型提示时它必须存在...
576i

13
@ 576i:iirc,也可以使用字符串。因此def foo(bar: 'Qux')等效于def foo(bar: Qux)它不需要立即加载类型。
Willem Van Onsem

2
@willem谢谢-我不知道。最好的是,pycharm自动补全仍然有效。.–
576i

3
@ cs95是的。所有类型提示均为+3.7。
thiras
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.