gpt4 book ai didi

python - 在 Python 中,如何输入提示 'has attribute' ?

转载 作者:行者123 更新时间:2023-12-04 01:09:43 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How should a python type hint require that a value has a given attribute?

(3 个回答)


1年前关闭。




考虑这个人为的例子;

@dataclass
class A:
name: str = "John"
....

@dataclass
class B:
name: str = "Doe"
问: 如何键入提示具有属性的对象,如下所示?
def print_name(obj: HasAttr['name'])
print(obj.name)
我了解关于显示您尝试过的内容的 SO 规则。我能提供的最好的就是我已经搜索了文档; Pep526 , PythonSheets , Docs ,并且我知道这个 SO Question .似乎没有任何帮助(或者我可能错过了。)
[编辑]我知道你可以通过继承到达那里,但我不想走那条路。

最佳答案

因此,您所描述的是结构类型。这与 python 类型系统所基于的基于类的名义子类型不同。然而,结构子类型是 Python 的动态鸭子类型的静态类型版本。
Python's typing system通过typing.Protocol 允许这种形式.
举个例子,假设我们有一个 Python 模块,test_typing.py :

from typing import Protocol
from dataclasses import dataclass

class Named(Protocol):
name: str


@dataclass
class A:
name: str
id: int


@dataclass
class B:
name: int

@dataclass
class C:
foo: str


def frobnicate(obj: Named) -> int:
return sum(map(ord, obj.name))


frobnicate(A('Juan', 1))
frobnicate(B(8))
frobnicate(C('Jon'))
使用 mypy 0.790 版:
(py38) juanarrivillaga@Juan-Arrivillaga-MacBook-Pro ~ % mypy test_typing.py
test_typing.py:28: error: Argument 1 to "frobnicate" has incompatible type "B"; expected "Named"
test_typing.py:28: note: Following member(s) of "B" have conflicts:
test_typing.py:28: note: name: expected "str", got "int"
test_typing.py:29: error: Argument 1 to "frobnicate" has incompatible type "C"; expected "Named"
Found 2 errors in 1 file (checked 1 source file)

关于python - 在 Python 中,如何输入提示 'has attribute' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65244798/

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