如何从字典中实例化 Class
How to Instantiate a Class from a Dictionary
给定一个 class,如何从字段字典中创建它的实例?这是一个例子来说明我的问题:
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}
)
请参阅 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
给定一个 class,如何从字段字典中创建它的实例?这是一个例子来说明我的问题:
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}
)
请参阅 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