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}
)
Aucun commentaire:
Enregistrer un commentaire