python笔记:dataclass

发布于:2024-05-04 ⋅ 阅读:(133) ⋅ 点赞:(0)

1 引子:其他类似实现方法的局限性

假设我们现在需要实现这样的内容:

name China
area 960
population 140967

1.1 tuple/list

country1_tuple=('China','960','140967')
country1_tuple[0]
#'China'

缺点:需要记住各个属性是list/tuple第几位的属性(基于位置)

1.2 字典

country1_dict={'name':'China',
              'area':960,
              'population':140967}
country1_dict['name']
#'China'
  • 不足
    • 不能用country1_dict.name的形式进行控制
    • 少值【country1_dict={'name':'China', 'area':960】一样可以创建成功

1.3 namedtuple

python 库整理: collections.namedtuple_python collections.namedtuple创建一个-CSDN博客

from collections import namedtuple

Country=namedtuple('Country1',['name','area','population'])

country1=Country('China',960,'140967')
country2=Country('Singapore',733,564)

country1
#Country1(name='China', area=960, population='140967')

country2.name
#'Singapore'
  • 弥补了字典的两个缺点
    • 可以用country2.name的形式
    • 少值会报错
  • 不足
    • 无法修改值

1.4 自定义类

class Country:
    def __init__(self,name,area,population):
        self.name=name
        self.area=area
        self.population=population
        
country1_class=Country('China',960,140967)
country1_class.name
#'China'


country1_class.name="PRC"
  • 解决了namedtuple无法修改值的问题
  • 不足:
    • __init__方法中重复代码 (示例中每个属性都需要写3遍)

2 数据类dataclass

  • 提供了一个简写__init__方法的语法糖. 
  • 类型注释是必填项
  • 默认值的传递方式和__init__方法的参数格式一致
from dataclasses import dataclass

@dataclass
class Country_dc:
    name:str
    area:int
    population:int=40
        
country_dc1=Country_dc('China',960,140967)
country_dc2=Country_dc('Singapore',733)


country_dc1
#Country_dc(name='China', area=960, population=140967)


country_dc2
#Country_dc(name='Singapore', area=733, population=40)

2.1 数据嵌套

from typing import List

@dataclass
class Countrys_dc:
    name:str
    countries:List[Country_dc]
country_lst=Countrys_dc('China & SG',[country_dc1,country_dc2])
country_lst
'''
Countrys_dc(name='China & SG', countries=[Country_dc(name='China', area=960, population=140967), Country_dc(name='Singapore', area=733, population=40)])
'''

2.2 数据类不可变

 要使数据类不可变,需要在创建类时设置frozen=True。

参考内容:Python中的数据类dataclass详解_python dataclass-CSDN博客


网站公告

今日签到

点亮在社区的每一天
去签到