TypedDict的默认值

huangapple go评论63阅读模式
英文:

Default values for TypedDict

问题

让我们考虑一下我有以下的 TypedDict:

class A(TypedDict):
    a: int
    b: int

为这个类设置默认值的最佳做法是什么?

我尝试添加一个构造函数,但似乎不起作用。

class A(TypedDict):
    a: int
    b: int
    def __init__(self):
        TypedDict.__init__(self)
        a = 0
        b = 1

编辑:
我不想使用 dataclass,因为我需要将数据序列化和反序列化为 JSON 文件,而 dataclasses 在这方面存在一些问题。

你认为呢?

英文:

Let's consider I have the following TypedDict:

class A(TypedDict):
    a: int
    b: int

What is the best practice for setting default values for this class?

I tried to add a constructor but it doesn't seem to work.

class A(TypedDict):
    a: int
    b: int
    def __init__(self):
        TypedDict.__init__(self)
        a = 0
        b = 1

EDIT:
I don't want to use dataclass because I need to serialize and deserialize to JSON files and dataclasses have some problem with it.

What do you think?

答案1

得分: 2

TypedDict 仅用于指定一个 dict 遵循特定的布局,而不是一个实际的类。当然,你可以使用 TypedDict 来创建一个符合特定布局的实例,但它不包含默认值。

一个可能的解决方案是向类添加一个 factory 方法。你可以使用这个 factory 方法来设置默认值。

from typing import TypedDict

class A(TypedDict):
    a: int
    b: int

    @classmethod
    def create(cls, a: int = 0, b: int = 1) -> A:
        return A(a=a, b=b)

a = A.create(a=4)
# {"a": 4, "b": 1}

如果不严格要求使用 dict,那么 @dataclass 适用于具有默认值的小对象。

from dataclasses import dataclass

@dataclass
class A:
    a: int = 0
    b: int = 1

如果需要从它们创建一个字典,你可以使用 asdict

from dataclasses import asdict

a = A(a=4)
asdict(a)  # {"a": 4, "b": 1}
英文:

TypedDict is only for specifying that a dict follows a certain layout, not an actual class. You can of course use a TypedDict to create an instance of that specific layout but it doesn't come with defaults.

One possible solution is to add a factory method to the class.
You could use this factory method instead to set defaults.

from typing import TypedDict

class A(TypedDict):
    a: int
    b: int

    @classmethod
    def create(cls, a: int = 0, b: int = 1) -> A:
        return A(a=a, b=b)

a = A.create(a=4)
# {"a": 4, "b": 1}

If having a dict is not a strict requirement then @dataclass is good having small objects with defaults.

from dataclasses import dataclass

@dataclass
class A:
    a: int = 0
    b: int = 1

If you need to create a dictionary from them, you can use asdict

from dataclasses import asdict

a = A(a=4)
asdict(a)  # {"a": 4, "b": 1}

huangapple
  • 本文由 发表于 2023年5月15日 15:38:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定