主要用于利用类型注解语法快速定义数据类 frozen=True: 默认创建的数据类是可修改的,不支持任何哈希操作,通过设置frozen=True,可设置为不可变类型 field(compare=False):当字段不用于比较运算,可设置compare=False

    1. from dataclasses import dataclass, field
    2. @dataclass(frozen=True)
    3. class UserInfo:
    4. first_name: str
    5. last_name: str
    6. phone_number: str
    7. created_date: str = field(compare=False)
    8. init_data = {
    9. 'first_name': 'wang',
    10. 'last_name': 'shunzhe',
    11. 'phone_number': '133xxxx',
    12. 'created_date': '20220725'
    13. }
    14. a = UserInfo(first_name='wang', last_name='shunzhe', phone_number='133xxxx', created_date='20220725')
    15. b = UserInfo(**init_data)
    16. # UserInfo(first_name='wang', last_name='shunzhe', phone_number='133xxxx', created_date='20220725')
    17. print(b)
    18. # 133xxxx
    19. print(b.phone_number)
    20. # dataclasses.FrozenInstanceError: cannot assign to field 'phone_number'
    21. b.phone_number = '1222xxx'
    22. print(b.phone_number)