dataclasses 模块

本节主要讲述dataclasses的dataclass,field

 

导入: from dataclasses import dataclass, field

 

1.This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.

举个例子:定义一个数据类,数据类中定义一个方法

from dataclasses import dataclass


@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        total_ct = self.unit_price * self.quantity_on_hand
        return total_ct

if __name__ == '__main__':
    a = InventoryItem("zhangsan", 2.0, 3)
    print(a)  # InventoryItem(name='zhangsan', unit_price=2.0, quantity_on_hand=3)
    print(a.total_cost())   # 6.0

 

①在total_cost()方法中,可以用self.unit_price......这种用法,就说明被dataclass装饰的类,根据类中定义的name,unit_price。。。会自动生成一个__init__方法,即:

会自动生成:(Note that this __init__ method is automatically added to the class)

def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

 

②类中定义的变量没有赋值时,可以实例化对象进行赋值,如上述的a对象

  类中定义的变量有赋值,可以实例化对象时,可以修改(参考默认参数),上面例子中 quantity_on_hand 定义format 为0,实例对象为3

③类中的所有参数都有默认值时,可以用fields方法获取每个变量的filed, 再进行field取值,

举例:

class InfoManage:
    """Info manage."""

    name: str = 'zhangsan'
    age: int = 23
    hight: float = 180.0


field_types = {field.name: getattr(InfoManage, field.name) for field in fields(InfoManage)}
print(field_types) # {'name': 'zhangsan', 'age': 23, 'hight': 180.0}

 

more to add......