python字典实例化对象_python--从字典实例化类

可以用于构建工厂模式,这里记录以下

def get_obj_from_dict(info_dict,parent=None,default_args=None):

r'''从字典中建立示例对象

Parameters

----------

info_dict : (dict)

必须有type键,值是需要实例化的类的名

parent : (str = None)

需要实例化的类的属于那个包名

default_args : (dict =None)

实例化的类的默认参数

'''

assert isinstance(info_dict, dict) and 'type' in info_dict

assert isinstance(default_args, dict) or default_args is None

args = info_dict.copy()

obj_type = args.pop('type')

if 'parent' in info_dict:

parent=args.pop('type')

if isinstance(obj_type,str):

if parent is not None:

obj_type = getattr(parent, obj_type)

else:

obj_type = sys.modules[obj_type]

elif not isinstance(obj_type, type):

raise TypeError('type must be a str or valid type, but got {}'.format(

type(obj_type)))

if default_args is not None:

for name, value in default_args.items():

args.setdefault(name, value)

return obj_type(**args)

```

标签:None,obj,parent,python,args,dict,化类,type,字典

来源: https://blog.csdn.net/sinat_24899403/article/details/95509374

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值