【发布时间】:2026-02-24 08:55:01
【问题描述】:
我正在运行 Python 3.8.10 并且有一个具有一些属性的数据类。其中一些具有默认值,但不是构造函数的一部分。
init 值设置为 False 的属性不会显示在对象字典中。
这是预期的行为吗?如何强制这些属性显示在 vars 中?
from dataclasses import dataclass, field
@dataclass
class Book:
name: str = field(default="", init=False)
author: str = field(default="", init=True)
b = Book()
b
> Book(name='', author='')
b.name
> ''
b.author
> ''
## name does not show up here
vars(b)
> {'author': ''}
b.__dict__
> {'author': ''}
【问题讨论】: