【发布时间】:2020-04-27 20:13:25
【问题描述】:
我想在 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 似乎可以使用不变量,这也是我的想法;我不希望各种Filters 相互兼容。无论如何,将contravariant=True 打到T doesn't work either 上。所以,
为什么协议需要逆变变量?还有,我如何进行这个 Python 代码类型检查?
【问题讨论】:
-
当我点击“运行”时,您的“也不起作用”链接显示“成功:在 1 个源文件中未发现问题”。
-
哦,等等,你以为
BadFilter会失败。逆变意味着BadFilter很好。可以过滤任意对象的过滤器可以过滤事件。 -
@user2357112supportsMonica
MyFilter过滤子类,BadFilter过滤超类。肯定其中之一应该失败?
标签: python python-typing