简体   繁体   中英

How to Instantiate a Class from a Dictionary

Given a class, how can an instance of it be created from a dictionary of fields? Here is an example to illustrate my question:

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

See How to create a class instance without calling initializer? to bypass the initializer. Then set the attributes from the dictionary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM