Python中定义一个数据类的正确方法是什么,该数据类同时具有自动生成的 __init__ 和来自值字典的附加 init2

Raa*_*mEE 3 python data-class python-dataclasses

在 Python 中,我有一个包含十多个成员的数据类。我用它创建一个字典并将其发布到 ElasticSearch 中

现在我想从 ElasticSearch获取一个字典并用它来初始化数据类。

自从:

  1. Python 不允许创建具有不同签名的第二个 __ init __ 。
  2. 我不想手动编写自动生成的 __ init __ 只是为了添加可选参数
  3. 我不想添加可选参数来接受字典,只是为了让 __ init __ 保持自动生成。

我想添加第二个方法init2,它将返回数据类的实例,并将传递的 dict 参数解析到自动生成的 __ init __ 方法中。


我会感谢您的意见来决定我下面建议的解决方案是否是正确的实施。

另外,这种实现可以被视为一种工厂吗?

谢谢。


跟进:由于我从 ES 请求中获取的 JSON\dictionary 是:

  1. 与数据类具有完全相同的关键字

  2. 是扁平的,id,没有嵌套对象。

我可以简单地将这些值作为 **dict 传递到自动生成的 __ init __ 方法中。

对于这个具体案例,请参阅下面我的回答:


from dataclasses import dataclass

@dataclass
class MyData:
    name: str
    age: int = 17

    @classmethod
    def init_from_dict(cls, values_in_dict: dict):
        # Original line using MyData was fixed to use cls, following @ForceBru 's comment
        # return MyData(values_in_dict['name'], age=values_in_dict['age'])
        return cls(values_in_dict['name'], age=values_in_dict['age'])

my_data_1: MyData = MyData('Alice')
print(my_data_1)

my_data_2: MyData = MyData('Bob', 15)
print(my_data_2)

values_in_dict_3: dict = {
    'name': 'Carol',
    'age': 20
}

my_data_3: MyData = MyData.init_from_dict(values_in_dict_3)
print(my_data_3)

# Another init which uses the auto-generated __init__ works in this specific
# case because the values' dict is flat and the keywords are the same as the
# parameter names in the dataclass.
# This allows me to do this
my_data_4: MyData = MyData(**values_in_dict_3)
Run Code Online (Sandbox Code Playgroud)

For*_*Bru 5

您的代码中存在潜在的错误。考虑一下:

class Thing:
    def __init__(self, a, b):
        self.a, self.b = a, b

    @classmethod
    def from_int(cls, value):
        return Thing(value, value + 1)

class AnotherOne(Thing):
    def __init__(self, a, b):
        self.a, self.b = a + 1, b + 2
Run Code Online (Sandbox Code Playgroud)

现在,如果你运行AnotherOne.from_int(6)你会得到一个Thing对象:

>>> AnotherOne.from_int(6)
<__main__.Thing object at 0x8f4a04c>
Run Code Online (Sandbox Code Playgroud)

...而您可能想创建一个AnotherOne对象!

要解决此问题,请像这样创建对象:

class Thing:
    ...

    @classmethod
    def from_int(cls, value):
        return cls(value, value + 1)  # Use `cls` instead of `Thing`
Run Code Online (Sandbox Code Playgroud)

我认为您的代码在其他方面都很好:实际上, 的用法之一classmethod是提供除使用 之外的其他方法来初始化类的实例__init__