【问题标题】:In Python, how do I type hint 'has attribute'? [duplicate]在 Python 中,如何输入提示“具有属性”? [复制]
【发布时间】:2020-12-11 11:17:39
【问题描述】:

考虑这个人为的例子;

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

@dataclass
class B:
    name: str = "Doe"

问:如何键入提示具有如下属性的对象?

def print_name(obj: HasAttr['name'])
    print(obj.name)

我了解关于展示您尝试过的内容的 SO 规则。我能提供的最好的就是我已经搜索了文档; Pep526PythonSheetsDocs,我知道这个SO Question。似乎没有任何帮助(或者我可能错过了。)

[Edit] 我知道你可以通过继承到达那里,但我不想走那条路。

【问题讨论】:

标签: python python-3.x type-hinting


【解决方案1】:

所以,您所描述的是结构类型。这与 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2018-03-24
    • 2019-10-19
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多