首页 > 解决方案 > 如何从字典中实例化一个类

问题描述

给定一个类,如何从字段字典创建它的实例?这是一个例子来说明我的问题:

from typing import Tuple, Mapping, Any


def new_instance(of: type, with_fields: Mapping[str, Any]):
    """How to implement this?"""
    return ...


class A:
    """Example class"""

    def __init__(self, pair: Tuple[int, int]):
        self.first = pair[0]
        self.second = pair[1]

    def sum(self):
        return self.first + self.second


# Example use of new_instance
a_instance = new_instance(
    of=A,
    with_fields={'first': 1, 'second': 2}
)

标签: pythonreflectioninstantiation

解决方案


请参阅如何在不调用初始化程序的情况下创建类实例?绕过初始化程序。然后从字典中设置属性。

def new_instance(of: type, with_fields: Mapping[str, Any]):
    obj = of.__new__(of)
    for attr, value in with_fields.items():
        setattr(obj, attr, value)
    return obj

推荐阅读