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

2024-06-01 01:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

def FuncA(arg: CustomClass):

或者是:

def FuncA(Arg:Type[CustomClass]):


Tags: 函数答案类型参数定义deftype方式
1条回答
网友
1楼 · 发布于 2024-06-01 01:18:18

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

就像写在关于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.

文档包括一个带有int类的示例:

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

相关问题 更多 >