【问题标题】:How to Instantiate a Class from a Dictionary如何从字典中实例化一个类
【发布时间】:2020-02-24 23:27:39
【问题描述】:

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

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

【问题讨论】:

  • 字典{'first': 1, 'second': 2}应该如何映射到元组[int, int]
  • @Barmar 它不应该映射到元组。我想绕过构造函数,直接初始化字段。
  • 如果类被定义为def __init__(self, first, second) 会更有意义。然后你可以在调用类时使用**with_fields
  • @Barmar 我故意没有这样定义它,因为通常构造函数可能不仅仅直接获取字段列表。我正在寻找一种即使在这种情况下也有效的解决方案。

标签: python reflection instantiation


【解决方案1】:

请参阅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

【讨论】:

  • 不应该是obj = of.__new__(of)吗?
  • @Stephane:我知道。
  • 是的,参数和类型注释混淆了。
猜你喜欢
  • 1970-01-01
  • 2018-08-09
  • 2012-12-23
  • 2019-06-08
  • 1970-01-01
  • 2020-12-15
  • 2021-10-13
相关资源
最近更新 更多