当前位置: 首页 > news >正文

Python 中 DAO 层使用泛型的探索

方法一:

from types import UnionType
from typing import TypeVar, Generic, TypeModelT = TypeVar('ModelT')def _new_cls_with_grm_generic_args(cls, __item):new_cls = type(f"{cls.__name__}[{__item.__name__}]", (cls,), {})new_cls._grm_generic_arg = __itemreturn new_clsclass GenericResolveMeta(type):def __getitem__(cls, __item):print('__getitem__')return _new_cls_with_grm_generic_args(cls, __item)class BaseDAO(Generic[ModelT], metaclass=GenericResolveMeta):"""DAO 泛型基类"""def __class_getitem__(cls, __item):print('__class_getitem__')return _new_cls_with_grm_generic_args(cls, __item)def __init__(self):only_one_arg = getattr(self, "_grm_generic_arg", None)if not only_one_arg:raise TypeError("ModelT must be assigned")if isinstance(only_one_arg, UnionType):raise TypeError("ModelT must not be a UnionType")self.model: Type[ModelT] = only_one_argclass Item(BaseDAO[str]):def __init__(self):super().__init__()item = Item()
print(item.model)  # 输出: <class 'str'># 对一个类使用方括号,首先检查其元类是否定义 __getitem__ 方法,有则调用,无则检查该类是否定义 __class_getitem__ 方法,有则调用,无则报错

方法二:

from types import UnionType
from typing import Generic, TypeVar, get_origin, get_args, TypeModelT = TypeVar('ModelT')class BaseDAO(Generic[ModelT]):"""DAO 泛型基类1. 一个类必须继承一个 BaseDAO 或者 BaseDAO 子类,不能继承多个BaseDAO 或者 BaseDAO 子类2. 泛型必须传入一个类型,通常为 SQLAlchemy 中模型,不可为 types.UnionType"""def __init__(self):orig_bases = getattr(self.__class__, '__orig_bases__', None)if not orig_bases:raise TypeError("__orig_bases__ is empty")target_bases = [c for c in orig_bases if issubclass(get_origin(c), BaseDAO)]if len(target_bases) != 1:raise TypeError(f"{self.__class__} must extend a BaseDAO or BaseDAO's subclass")args = get_args(target_bases[0])if not len(args) == 1:raise RuntimeError("ModelT must be assigned")only_one_arg = args[0]if isinstance(only_one_arg, UnionType):raise TypeError("ModelT must not be a UnionType")self.model: Type[ModelT] = only_one_argclass Item(BaseDAO[str]):...item = Item()
print(item.model)
http://www.dtcms.com/a/168693.html

相关文章:

  • 接口测试实战指南:从入门到精通的质量保障之道
  • Linux系统:详解文件描述符与重定向原理以及相关接口(open,read,write,dup2)
  • 分布式理论:常见分布式协议的概览与解析
  • 51c大模型~合集123
  • C++ 复习
  • AI驱动文字冒险游戏
  • 第 12 届蓝桥杯 C++ 青少组中 / 高级组省赛 2021 年真题
  • 0基础 | STM32 | STM32F103C8T6开发板 | 项目开发
  • #以梦为楫,共航中医传承新程
  • 芯片中的pad、strap和probe
  • Proxmox VE 8.4 显卡直通完整指南:NVIDIA 2080 Ti 实战
  • 深度学习与 PyTorch 基础
  • WindowsPE文件格式入门10.TLS表
  • Day108 | 灵神 | 合并两个有序链表
  • Matlab自学笔记
  • 网工_UDP协议
  • JavaWeb学习打卡-Day7-正向代理、反向代理、Nginx
  • C++--入门基础
  • JVM 如何使用性能分析工具定位代码中的性能问题?
  • 基于bert的情感分析程序
  • 【安装指南】DevC++的安装和使用(超级详细)
  • 【Linux】Linux奇技淫巧
  • 从0开始建立Github个人博客(hugoPaperMod)
  • ubuntu的libc 库被我 sudo apt-get --reinstall install libc6搞没了
  • AI人工智能的接入和使用
  • Matplotlib核心课程-2
  • 【符号调制技术与载波调制技术】
  • Controller层接收参数方式
  • Java学习手册:Spring Boot 自动配置与快速开发
  • RISCV的smstateen-ssstateen扩展