如何从字典实例化类

2024-04-23 11:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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}
)

Tags: ofinstanceselffieldsnewreturndefwith
1条回答
网友
1楼 · 发布于 2024-04-23 11:19:59

请参见How to create a class instance without calling initializer?以绕过初始值设定项。然后从字典中设置属性

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

相关问题 更多 >