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

hhp*_*ram 63 python type-hinting user-defined-types python-3.x

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

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

def FuncA(arg: CustomClass):

或者它会是:

def FuncA(Arg:Type[CustomClass]):

Wil*_*sem 76

前者是正确的,如果arg接受一个实例CustomClass:

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass
Run Code Online (Sandbox Code Playgroud)

如果你想要CustomClass本身(或子类型),那么你应该写:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself
Run Code Online (Sandbox Code Playgroud)

就像它写在关于打字的文档中一样:

class typing.Type(Generic[CT_co])
Run Code Online (Sandbox Code Playgroud)

带注释的变量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]'
Run Code Online (Sandbox Code Playgroud)

  • @ 576i:iirc,你也可以用一个字符串.所以`def foo(bar:'Qux')`相当于`def foo(bar:Qux)`,除了它不需要立即加载类型. (8认同)
  • 请注意,如果您在同一个文件中有该类,则在评估类型提示时它需要存在... (4认同)
  • @cs95 是的。所有类型提示均为+3.7。 (3认同)
  • @willem谢谢 - 我不知道.什么是最好的,pycharm自动完成仍然有效.. (2认同)

thi*_*ndy 30

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

from typing import Dict

foo: Dict[str, str] = { "bar": "baz" }
Run Code Online (Sandbox Code Playgroud)

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

foo: dict[str, str] = { "bar": "baz" }
Run Code Online (Sandbox Code Playgroud)

此功能在 python 3.9+ 中可用,如果使用from __future__ import annotations.

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

def FuncA(arg: type[CustomClass]):
Run Code Online (Sandbox Code Playgroud)

  • 这是 Python 3.9 的正确答案,因为 Willem Van Onsem 的答案中显示的 [`typing.Type`](https://docs.python.org/3/library/typing.html#typing.Type) 的使用已被弃用。 (4认同)