父类中接收子类实例为参数的类型提示如何定义?
为父类类方法的子类实例参数添加正确类型提示
针对你遇到的问题,有两种简洁的解决方案,无需逐个指定子类类型:
方案1:兼容Python 3.9及以上的泛型实现
通过TypeVar和Generic绑定父类与子类的类型关系,让类型检查工具自动识别子类实例:
import pandas as pd from typing import TypeVar, Generic # 定义绑定到ParentPandasModel的类型变量,限制只能是自身或子类 T = TypeVar('T', bound='ParentPandasModel') class ParentPandasModel(pd.DataFrame, Generic[T]): """Parent class for all the models that are based on pandas""" @classmethod def validate_dataframe(cls, arg1: T) -> bool: """ Checks if the instance has all needed columns etc.""" # 示例验证逻辑:检查子类定义的列是否全部存在 required_columns = [v for k, v in cls.__dict__.items() if k.startswith("column")] is_data_frame_valid = all(col in arg1.columns for col in required_columns) return is_data_frame_valid class ChildModel(ParentPandasModel["ChildModel"]): """ dataframe model """ column1 = "price" column2 = "number" column3 = "date" # 测试调用,类型检查工具会自动识别df为ChildModel实例 df = ChildModel({"price": [100], "number": [5], "date": ["2024-01-01"]}) ChildModel.validate_dataframe(df) # 无类型报错
核心逻辑:
TypeVar('T', bound='ParentPandasModel')限定T只能是ParentPandasModel或其子类- 父类继承
Generic[T],让子类继承时绑定自身类型 - 类方法的
arg1: T会自动对应子类的实例类型,类型检查工具可正确识别
方案2:Python 3.11+ 简化版(使用Self类型)
Python 3.11引入的Self类型可直接指代调用类方法的子类实例,无需额外泛型声明:
import pandas as pd from typing import Self class ParentPandasModel(pd.DataFrame): """Parent class for all the models that are based on pandas""" @classmethod def validate_dataframe(cls, arg1: Self) -> bool: """ Checks if the instance has all needed columns etc.""" required_columns = [v for k, v in cls.__dict__.items() if k.startswith("column")] is_data_frame_valid = all(col in arg1.columns for col in required_columns) return is_data_frame_valid class ChildModel(ParentPandasModel): """ dataframe model """ column1 = "price" column2 = "number" column3 = "date" # 测试调用 df = ChildModel({"price": [100], "number": [5], "date": ["2024-01-01"]}) ChildModel.validate_dataframe(df) # 无类型报错
这种方式更简洁,Self会自动匹配调用该方法的子类实例类型,完美适配你的场景。
内容的提问来源于stack exchange,提问作者Antoine Ga
相关产品推荐
相关产品推荐

