我正在尝试使已实现的泛型类型的子类在子类中具有更严格的泛型类型。简化后,我的代码如下:
>>> from typing import Generic, TypeVar
>>>
>>> T = TypeVar('T')
>>>
>>>
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> class X(Generic[T]):
... pass
...
>>> class Y(X[A]):
... pass
...
>>> class Z(Y[B]):
... pass
...
Traceback (most recent call last):
File "<input>", line 1, in <module>
class Z(Y[B]):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 251, in inner
return func(*args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 838, in __class_getitem__
_check_generic(cls, params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 201, in _check_generic
raise TypeError(f"{cls} is not a generic class")
TypeError: <class '__main__.Y'> is not a generic class
以下内容似乎有效,但我不确定这是否正确:
>>> class Z(Y, X[B]):
... pass
...