使用用户定义的类输入提示

时间:2017-06-20 22:32:32

标签: python python-3.x user-defined-types type-hinting

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

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

def FuncA(arg: CustomClass):

或者它会是:

def FuncA(Arg:Type[CustomClass]):

2 个答案:

答案 0 :(得分:55)

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

使用C注释的变量可以接受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 :(得分:0)

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+ 中也可用。

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

def FuncA(arg: type[CustomClass]):