gpt4 book ai didi

python - 使用用户定义的类键入提示

转载 作者:IT老高 更新时间:2023-10-28 20:30:59 26 4
gpt4 key购买 nike

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

然后假设在某个函数中,将其称为 FuncA(arg),我有一个名为 arg 的参数。输入提示 FuncA 的正确方法是:

def FuncA(arg: CustomClass):

还是这样:

from typing import Type

def FuncA(Arg:Type[CustomClass]):

最佳答案

前者是正确的,如果 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 的文档中所写的那样:

<b>class typing.Type(Generic[CT_co])</b>

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]'

关于python - 使用用户定义的类键入提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44664040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com