如何解决 python3.11 dataclass 无法嵌套的问题?

如何解决 python3.11 dataclass 无法嵌套的问题?

from dataclasses import dataclass

@dataclass

class Address:

street: str | None = None

city: str | None = None

state: str | None = None

@dataclass

class Person:

name: str

age: int

address: Address = Address()

上面的代码,在 python3.10 下面没有问题

但是在 python3.11 上运行,就会报错

Traceback (most recent call last):

File "/Users/ponponon/Desktop/code/me/ideaboom/3.py", line 11, in <module>

@dataclass

^^^^^^^^^

File "/opt/homebrew/Cellar/python@3.11/3.11.4/Frameworks/Python.framework/Versions/3.11/lib/python3.11/dataclasses.py", line 1230, in dataclass

return wrap(cls)

^^^^^^^^^

File "/opt/homebrew/Cellar/python@3.11/3.11.4/Frameworks/Python.framework/Versions/3.11/lib/python3.11/dataclasses.py", line 1220, in wrap

return _process_class(cls, init, repr, eq, order, unsafe_hash,

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/opt/homebrew/Cellar/python@3.11/3.11.4/Frameworks/Python.framework/Versions/3.11/lib/python3.11/dataclasses.py", line 958, in _process_class

cls_fields.append(_get_field(cls, name, type, kw_only))

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "/opt/homebrew/Cellar/python@3.11/3.11.4/Frameworks/Python.framework/Versions/3.11/lib/python3.11/dataclasses.py", line 815, in _get_field

raise ValueError(f'mutable default {type(f.default)} for field '

ValueError: mutable default <class '__main__.Address'> for field address is not allowed: use default_factory


回答:

from dataclasses import dataclass, field

@dataclass

class Address:

street: str | None = None

city: str | None = None

state: str | None = None

@dataclass

class Person:

name: str

age: int

address: Address = field(default_factory=Address)

以上是 如何解决 python3.11 dataclass 无法嵌套的问题? 的全部内容, 来源链接: utcz.com/p/938932.html

回到顶部