我想在 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;
}
}
这是我的尝试:
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
彼此兼容。无论如何,打巴掌contravariant=True
onto T
. So,
为什么协议需要逆变变量?并且,如何进行 Python 代码类型检查?
协议不允许这样做,因为它破坏了子类型的传递性。看PEP 544 https://www.python.org/dev/peps/pep-0544/#overriding-inferred-variance-of-protocol-classes.
如果你有以下两个类:
class A:
def method(self, arg: int):
pass
class B(A):
def method(self, arg: object):
pass
then B
是一个有效的子类A
, 因为B.method
可以接受任何参数A.method
能。但是,如果您可以引入以下协议:
T = typing.TypeVar('T')
class Proto(typing.Protocol[T]):
def method(self, arg: T):
pass
then A
会满足Proto[int]
, but B
不会,由于不变性T
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)