Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.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 3.x 仅适用于任意类的Python类型提示(不适用于类实例或任何其他非类类型)_Python 3.x_Python Typing - Fatal编程技术网

Python 3.x 仅适用于任意类的Python类型提示(不适用于类实例或任何其他非类类型)

Python 3.x 仅适用于任意类的Python类型提示(不适用于类实例或任何其他非类类型),python-3.x,python-typing,Python 3.x,Python Typing,我有一个方法可以检查和处理任意类(仅类,而不是类实例或任何其他非类类型)的源。这些类可以来自任何标准库、第三方库或用户定义的类 但是,我不知道使用typing模块注释类参数类型的正确方法。我不认为键入.Type是正确的,因为它也适用于对象: >>> class A: pass >>> a = A() >>> def test(cl: typing.Type) -> typing.Type: ... return type(cl

我有一个方法可以检查和处理任意类(仅类,而不是类实例或任何其他非类类型)的源。这些类可以来自任何标准库、第三方库或用户定义的类

但是,我不知道使用
typing
模块注释类参数类型的正确方法。我不认为
键入.Type
是正确的,因为它也适用于对象:

>>> class A: pass
>>> a = A()

>>> def test(cl: typing.Type) -> typing.Type:
...     return type(cl)

>>> test(A)
>>> type
>>> isinstance(A, typing.Type)
>>> True

>>> test(a)
>>> type
>>> isinstance(A, typing.Type)
>>> False

>>> test('A')
>>> str
>>> isinstance(A, typing.Type)
>>> False

注释应该这样工作吗?带注释的参数不应该限制方法的调用,以仅识别正确类型的参数吗?

使用“类型”确实是正确的。例如,如果您尝试使用类型检查器(例如

从键入导入类型
甲级:及格
#更准确地说,类型签名是
#“(cls:Type[T])->Type[Type[T]]”,其中T是某种类型变量。
def测试(cls:类型)->类型:
返回类型(cls)
a=a()
测试(A)
测试(a)
测试('A')
…您最终会出现以下错误,我相信这正是您所期望的:

test.py:13: error: Argument 1 to "test" has incompatible type "A"; expected "Type[Any]"
test.py:14: error: Argument 1 to "test" has incompatible type "str"; expected "Type[Any]"
Found 2 errors in 1 file (checked 1 source file)

如果您询问为什么Python本身没有检查这些类型提示以及为什么需要使用第三方类型检查器,请参阅。

类型提示只是……提示……它们向IDE之类的对象提示对象可能是什么类型。但是它们不是运行时代码的一部分,它们不强制对象类型必须是特定的。谢谢,这很好。我想也许有一个只适用于类的特殊类型提示会很有用。就像生成器(
typing.Generator
)和迭代器(
typing.Iterator
)有单独的类型提示一样,即使生成器是迭代器。
isinstance((范围(10)中的x代表x)),typing.Iterator)
->
True
很抱歉,我删除了我的评论来重写它,geneartors返回迭代器,但它们不在自己的iteraotrs中