编程语言
首页 > 编程语言> > 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