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)
就像它写在关于打字的文档中一样:
Run Code Online (Sandbox Code Playgroud)class typing.Type(Generic[CT_co])
带注释的变量
C
可以接受类型的值C
.相反,带注释Type[C]
的变量可以接受类本身的值 - 具体来说,它将接受类的对象C
.
该文档包含int
该类的示例:
Run Code Online (Sandbox Code Playgroud)a = 3 # Has type 'int' b = int # Has type 'Type[int]' c = type(a) # Also has type 'Type[int]'
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)