如何指定Python数据类可调用成员类型以接受子类实例
解决方案
要实现派生类的handler能接受自身实例作为参数,你需要借助泛型TypeVar来实现自引用的类型注解,Python 3.7可以通过以下方式解决:
步骤说明
- 定义一个绑定到
Base类的TypeVar,用于表示当前类(或派生类)的实例类型 - 将
Base类改为泛型类,继承Generic[T] - 把
handler的类型注解改为Callable[[T], str],让它能接受泛型参数对应的实例类型 - 派生类
Specific继承Base[Specific],明确泛型参数为自身类型
修改后的代码
from __future__ import annotations import dataclasses as dc from typing import TypeVar, Generic, Callable # 定义绑定到Base的TypeVar,用于表示当前类实例 T = TypeVar('T', bound='Base') @dc.dataclass class Base(Generic[T]): name: str handler: Callable[[T], str] @dc.dataclass class Specific(Base[Specific]): specific: str # 符合类型要求的处理函数 def specific_handler(v: Specific) -> str: return f"{v.specific}" # 现在赋值不会触发类型错误 sg = Specific(name="two", handler=specific_handler, specific="extra info") # 正常使用handler assert("extra info" == sg.handler(sg))
细节解释
from __future__ import annotations:Python 3.7中启用该特性后,注解会以字符串形式存储,避免前置引用的问题(比如TypeVar绑定'Base'时无需提前定义类)TypeVar('T', bound='Base'):限制T只能是Base或其派生类的类型,保证类型安全Base(Generic[T]):将Base转为泛型类,T会被派生类指定为自身类型,从而让handler的参数类型匹配派生类实例
内容的提问来源于stack exchange,提问作者mlamb
相关产品推荐
相关产品推荐

