发表于:2018-06-25 15:47:21
更新于:2018-06-25 15:47:21

Python3.7.0增加了一个dataclasses模块,包含了装饰器dataclass()dataclass() 提供了一种方式来定义数据类,数据类通过类变量注解的形式来描述,它的构造函数和其他 魔术方法,如__repr__()__eq__()__hash__()会被自动生成。


The new dataclass() decorator provides a way to declare data classes. A data class describes its attributes using class variable annotations. Its constructor and other magic methods, such as __repr__(), __eq__(), and __hash__() are generated automatically.


from dataclasses import dataclass  # 官方示例没这句

class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # 打印出 "Point(x=1.5, y=2.5, z=0.0)"