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}
)
解决方案
请参阅如何在不调用初始化程序的情况下创建类实例?绕过初始化程序。然后从字典中设置属性。
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
推荐阅读
- scala - 如何在 Scala 中使用 Phantom-dsl 从 Apache Cassandra 同步检索数据?
- c# - 我怎样才能使这段代码更通用
- ranking - 如何实现个性化的Feed排名?
- c - 将参数传递给unix中的自定义系统调用
- python-3.6 - 我希望我的代码每秒钟执行一次,并绘制每 n 秒后将更改的数据
- c - 在 OpenMP 中计算矩阵的条目
- idris - Idris 中 Gcd 的总定义
- python-sphinx - 是否应该转义自定义指令的参数?
- python - 为什么chain.from_iterable 不遍历int 列表?
- android - 通过 LAN Wi-Fi 网络从麦克风流式传输音频