gpt4 book ai didi

python - 在 Python 中定义接口(interface)

转载 作者:行者123 更新时间:2023-12-05 02:31:24 24 4
gpt4 key购买 nike

我想知道我们是否可以使用 typing 包来生成“接口(interface)”的定义,即 Python 3 中的类/对象。

似乎在 Python 中定义“接口(interface)”的通常方法是使用使用 ABC 定义的抽象类,并将其用作类型参数。但是,由于 Python 是动态类型的,因此完全抽象类型是一个接口(interface),只不过是 python 的类型提示。在运行时,我希望所述接口(interface)的影响为零。基类可以具有继承的方法,这不是我想要的。

我在很大程度上基于我使用 TypeScript 的经验 - 它使我们能够通过 interfacetype 关键字非常轻松地定义对象类型,但那些是仅供类型检查器使用。

让我用一个例子更清楚地说明我的用例:

假设我定义了一个函数 foo 如下:

def foo(bar):
nums = [i for i in range(10)]
result = bar.oogle(nums)
return result
因此,

foo 是一种期望接收对象实例的方法,该对象必须具有接受整数列表的方法 oogle。我想向调用者说明这是 foobar 的期望,但是 bar 可以是任何类型。

最佳答案

PEP544引入了 Protocol 类,可用于定义接口(interface)。

from typing import Any, List, Protocol

class Bar(Protocol):
def oogle(self, quz: List[int]) -> Any:
...

def foo(bar: Bar):
nums = [i for i in range(10)]
result = bar.oogle(nums)
return result

如果您使用 Python 执行脚本,您将看不到任何差异。您需要使用 Mypy 运行脚本,这是一个支持协议(protocol)类的静态类型检查器。

关于python - 在 Python 中定义接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71531417/

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