gpt4 book ai didi

python - 如何在 Python 中创建通用接口(interface)?

转载 作者:行者123 更新时间:2023-12-03 23:07:29 24 4
gpt4 key购买 nike

我想在 Python 中创建与此等效的内容:

static class Event {}

static class MyEvent extends Event {}

interface Filter<E extends Event> {
boolean filter(E event);
}

static class MyFilter implements Filter<MyEvent> {
@Override public boolean filter(MyEvent event) {
return true;
}
}

这是我的尝试 (mypy-play) :

from typing import TypeVar, Protocol

class Event:
pass

class MyEvent(Event):
pass

E = TypeVar("E", bound=Event)

class Filter(Protocol[E]):
def filter(self, event: E) -> bool:
raise NotImplementedError

class MyFilter(Filter):
def filter(self, event: MyEvent) -> bool: # should be ok
raise NotImplementedError

class BadFilter(Filter):
def filter(self, event: object) -> bool: # should fail
raise NotImplementedError

...失败了 main.py:11: error: Invariant type variable 'E' used in protocol where contravariant one is expected .除非我有误解,否则 Java 似乎可以使用不变量,这也是我的想法;我不要各种 Filter s 相互兼容。无论如何,打耳光 contravariant=True转至 T doesn't work either .所以,

为什么协议(protocol)需要逆变变量?而且,我如何进行这个 Python 代码类型检查?

最佳答案

协议(protocol)不允许这样做,因为它破坏了子类型的传递性。见 PEP 544 .

如果你有以下两个类:

class A:
def method(self, arg: int):
pass

class B(A):
def method(self, arg: object):
pass

然后 BA 的有效子类, 因为 B.method可以接受任何参数 A.method能够。但是,如果您可以引入以下协议(protocol):
T = typing.TypeVar('T')

class Proto(typing.Protocol[T]):
def method(self, arg: T):
pass

然后 A将满足 Proto[int] , 但是 B不会,因为 T 的不变性.

关于python - 如何在 Python 中创建通用接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61467673/

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