主要用于利用类型注解语法快速定义数据类 frozen=True: 默认创建的数据类是可修改的,不支持任何哈希操作,通过设置frozen=True,可设置为不可变类型 field(compare=False):当字段不用于比较运算,可设置compare=False
from dataclasses import dataclass, field
@dataclass(frozen=True)
class UserInfo:
first_name: str
last_name: str
phone_number: str
created_date: str = field(compare=False)
init_data = {
'first_name': 'wang',
'last_name': 'shunzhe',
'phone_number': '133xxxx',
'created_date': '20220725'
}
a = UserInfo(first_name='wang', last_name='shunzhe', phone_number='133xxxx', created_date='20220725')
b = UserInfo(**init_data)
# UserInfo(first_name='wang', last_name='shunzhe', phone_number='133xxxx', created_date='20220725')
print(b)
# 133xxxx
print(b.phone_number)
# dataclasses.FrozenInstanceError: cannot assign to field 'phone_number'
b.phone_number = '1222xxx'
print(b.phone_number)