Python 使用用户定义的类键入提示
似乎找不到确切的答案。我想为一个函数做一个类型提示,类型是我定义的某个自定义类,称之为Python 使用用户定义的类键入提示,python,python-3.x,types,type-hinting,user-defined-types,Python,Python 3.x,Types,Type Hinting,User Defined Types,似乎找不到确切的答案。我想为一个函数做一个类型提示,类型是我定义的某个自定义类,称之为CustomClass() 然后让我们假设在某个函数中,将其称为FuncA(arg),我有一个参数名为arg。键入提示FuncA的正确方法是: def FuncA(arg: CustomClass): 或者是: def FuncA(Arg:Type[CustomClass]): 如果arg接受CustomClass的实例,则前者是正确的: def FuncA(arg: CustomClass): #
CustomClass()
然后让我们假设在某个函数中,将其称为FuncA(arg)
,我有一个参数名为arg
。键入提示FuncA
的正确方法是:
def FuncA(arg: CustomClass):
或者是:
def FuncA(Arg:Type[CustomClass]):
如果
arg
接受CustomClass
的实例,则前者是正确的:
def FuncA(arg: CustomClass):
# ^ instance of CustomClass
如果需要类自定义类本身(或子类型)
,则应编写:
from typing import Type # you have to import Type
def FuncA(arg: Type[CustomClass]):
# ^ CustomClass (class object) itself
就像文档中写的关于:
类型是否来自py3.6及更高版本?我刚刚得到一个namererror
。请注意,如果您在同一个文件中有该类,则它需要在计算类型提示时存在…@576i:iirc,您还可以使用字符串。所以def-foo(bar:Qux')
等同于def-foo(bar:Qux)
,只是它不需要立即加载类型。@willem谢谢-我不知道这一点。最好的是,pycharm自动完成功能仍然有效。@cs95是的。所有类型提示均为+3.7。
class typing.Type(Generic[CT_co])
a = 3 # Has type 'int'
b = int # Has type 'Type[int]'
c = type(a) # Also has type 'Type[int]'