dataclass-数据类
在通常我们设计一个类时,需要初始化一些属性,如:
1 2 3 4
| class Car: def __init__(self, origin, auto): self.origin = origin self.auto = auto
|
- 当有了 dataclass 后就可以使用装饰器
@dataclass来实现
1 2 3 4 5 6 7 8 9 10 11
| @dataclass class Car: origin: str auto: bool
porsche = Car("Germany", True) print(porsche) benz = Car("Germany", True) print(benz)
print(porsche == benz)
|
1 2 3 4 5 6 7
| @dataclass class Car: origin: str auto: bool = True
porsche = Car("Germany") print(porsche)
|
1 2 3 4 5 6 7
| @dataclass(frozen=True) class Car: origin: str auto: bool
porsche = Car("Germany", True) porsche.auto = False
|
field()定制属性,可以看一下 field 的源代码
1 2 3 4 5 6 7 8 9 10 11
| @dataclass(frozen=True) class Car: origin: str auto: bool = True age: int = field(default=5, init=False, repr=False)
def __post_init__(self): self.auto = self.age < 5
porsche = Car("Germany", False) print(porsche)
|
- 排序,
order=True默认按照第一个属性进行排序,
1 2 3 4 5 6 7 8 9 10
| @dataclass(order=True) class Car: origin: str auto: bool
porsche = Car("Germany", True) benz = Car("Germany", False) cars = [porsche, benz] sorted(cars) print(cars)
|
- 当想依照另一个属性进行排序时,有两种方法
- 在类中创建一个不参与 init 与 repr 的变量,并放到第一个参数位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @dataclass(order=True) class Car: sortIndex: int = field(init=False, repr=False) origin: str age: int auto: bool = True
def __post_init__(self): self.sortIndex = self.age
porsche = Car("Germany", 4, True) benz = Car("Germany", 5, False) cars = [porsche, benz] cars = sorted(cars) print(cars)
|
- 另一个方法就是直接使用`sort()`方法中的`key=operator.attrgetter('属性名')`来实现按照哪一个属性进行排序`建议使用这个`
1 2 3 4 5 6 7 8 9 10 11
| @dataclass() class Car: origin: str age: int auto: bool = True
porsche = Car("Germany", 4, True) benz = Car("Germany", 5, False) cars = [porsche, benz] cars.sort(key=operator.attrgetter('age')) print(cars)
|
更新: 2024-01-10 21:24:23
原文: https://www.yuque.com/zacharyblock/cx2om6/ehmlkmargqm4bti5
Author:
Zachary Block
Permalink:
http://blockzachary.cn/blog/267352415/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE