gpt4 book ai didi

python - 打字。任何与对象?

转载 作者:IT老高 更新时间:2023-10-28 21:09:42 28 4
gpt4 key购买 nike

在打字时使用 typing.Anyobject 有什么区别吗?例如:

def get_item(L: list, i: int) -> typing.Any:
return L[i]

相比:

def get_item(L: list, i: int) -> object:
return L[i]

最佳答案

是的,有区别。尽管在 Python 3 中,所有对象都是 object 的实例,包括 object 本身,但只有 Any 记录了返回值应该被类型检查器忽略.

Any 类型的文档字符串声明对象是 Any 的子类,反之亦然:

>>> import typing
>>> print(typing.Any.__doc__)
Special type indicating an unconstrained type.

- Any object is an instance of Any.
- Any class is a subclass of Any.
- As a special case, Any and object are subclasses of each other.

然而,一个适当的类型检查器(一个超越 isinstance() 检查的检查器,它检查对象是如何在函数中实际使用的)可以很容易地反对 object,其中 Any 始终被接受。

来自 Any type documentation :

Notice that no typechecking is performed when assigning a value of type Any to a more precise type.

Contrast the behavior of Any with the behavior of object. Similar to Any, every type is a subtype of object. However, unlike Any, the reverse is not true: object is not a subtype of every other type.

That means when the type of a value is object, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error.

来自 mypy 文档部分 Any vs. object :

The type object is another type that can have an instance of arbitrary type as a value. Unlike Any, object is an ordinary static type (it is similar to Object in Java), and only operations valid for all types are accepted for object values.

object 可以是 cast到一个更具体的类型,而 Any 真的意味着 anything go 并且类型检查器不参与该对象的任何使用(即使您稍后将此类对象分配给一个名称经过类型检查)。

您已经通过接受 list 将您的函数绘制成一个未键入的角落,这归结为与 List[Any] 相同。类型检查器在那里脱离并且返回值不再重要,但是由于您的函数接受包含 Any 对象的列表,因此正确的返回值将是 Any 这里。

要正确参与类型检查代码,您需要将输入标记为 List[T](一个通用类型的容器),以便类型检查器能够关心返回值。在您的情况下,这将是 T 因为您正在从列表中检索一个值。从 TypeVar 创建 T:

from typing import TypeVar, List

T = TypeVar('T')

def get_item(L: List[T], i: int) -> T:
return L[i]

关于python - 打字。任何与对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817081/

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