经过更多研究后,我找到了一个解决方案:协议。由于它们还不是完全稳定(Python 3.6 还没有),因此必须从typing_extensions
模块。
import typing
from typing import Any
from typing_extensions import Protocol
from abc import abstractmethod
C = typing.TypeVar("C", bound="Comparable")
class Comparable(Protocol):
@abstractmethod
def __eq__(self, other: Any) -> bool:
pass
@abstractmethod
def __lt__(self: C, other: C) -> bool:
pass
def __gt__(self: C, other: C) -> bool:
return (not self < other) and self != other
def __le__(self: C, other: C) -> bool:
return self < other or self == other
def __ge__(self: C, other: C) -> bool:
return (not self < other)
现在我们可以将类型定义为:
C = typing.TypeVar("C", bound=Comparable)
class Bounded(object):
def __init__(self, minValue: C, maxValue: C) -> None:
assert minValue <= maxValue
self.__minValue = minValue
self.__maxValue = maxValue
Mypy 很高兴:
from functools import total_ordering
@total_ordering
class Test(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
FBounded(Test(1), Test(10))
FBounded(1, 10)