python 字典转对象实现

本篇博客参考链接
可用于 数据库查询结果比如fetchone将单行数据转化为已定义的类对象,前提你返回的数据与类定义中一一对应

def dict_to_class(cls, kwargs):
    """
  cls : 类名称
  kwargs: 类参数
  """
    return cls(**kwargs)
# 样例
a = {'id': 1, 'username': 2, 'password': '3'}
c = dict_to_class(User, a)
print(c)

实体类定义
实体类定义
运行结果
运行结果

© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
原文地址:https://www.cnblogs.com/xp-thebest/p/14348704.html