Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用用户定义的类键入提示_Python_Python 3.x_Types_Type Hinting_User Defined Types - Fatal编程技术网

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