python-3.x - 将python泛型传递给父类?
问题描述
我有一个声明为泛型的父类,一个抽象子类和该子类的具体实现,它声明了泛型类型:
MyType = TypeVar('MyType')
class A(Generic[MyType]):
a: MyType
class B(Generic[MyType], A[MyType]):
pass
class C(B[int]):
pass
但这不会将泛型声明从 C 转发到 A,因此 a 的类型不是 int。有没有正确的方法来做到这一点?尝试搜索 SO 和 python 文档,但找不到任何东西。
解决方案
A
你有一个类变量,所以它在类的所有实例之间共享。如果您尝试键入提示 this,那么您在任何时候创建一个新的A
.
例如a
这里有什么类型:
class A(Generic[MyType]):
a: MyType
class A1(A[str]):
pass
class A2(A[int]):
pass
如果你想代表一个成员变量,A
那么你可以这样做:
class A(Generic[MyType]):
def __init__(self, a: MyType):
self.val = a
class B(Generic[MyType], A[MyType]):
def __init__(self, b: MyType):
A.__init__(self, b)
class C(B[int]):
def __init__(self, c: int):
B.__init__(self, c)
class D(B[str]):
def __init__(self, d: str):
B.__init__(self, d)
在这里,我们有两个类C
和D which both have different generics
int and
str`,并且类型提示有效,因为我们正在创建具有不同泛型的子类。
希望6个月后这可能会有所帮助:)
推荐阅读
- python - Notepad ++的Python缩进插件不自动缩进
- css - 为什么我的 CSS 网格不会填满整个屏幕?
- ios - How to display the song selected album artwork to an ImageView in Swift
- reactjs - React Bootstrap - [HMR] 等待来自 WDS 错误的更新信号
- javascript - 如何在 react-native (web/android/ios) 中的图像上创建链接?
- laravel - [Route: patients.destroy] [URI: {language}/patients/{patient}] 缺少必需的参数。(资源/视图/患者/index.blade.php)
- python - IMAP 消息获取 UnicodeDecodeError 'utf-8' codec can't decode
- python - Python pd.read_csv:如何通过循环读取文件?
- sql - 在 PostgreSQL 数据库上更新查询间歇性缓慢
- javascript - 如果存在则更新 Many,否则为每个不存在的 LeadId 创建一个新 Document