Skip to Content
流畅的Python(第2版)
book

流畅的Python(第2版)

by Luciano Ramalho
April 2023
Intermediate to advanced
769 pages
25h 16m
Chinese
Posts & Telecom Press
Content preview from 流畅的Python(第2版)
123
5
数据类构建器
数据类就像小孩子。作为一个起点很好,但若要让它们像成熟的对象那样参与整
个系统的工作,它们就必须承担一定责任。
——
Martin Fowler
Kent Beck
1
Python
提供了几种构建简单类的方式,这些类只是字段的容器,几乎没有额外功能。这种
模式称为“数据类”(
data
class
),
dataclasses
包就支持该模式。本章介绍以下
3
个可简
化数据类构建过程的类构建器。
collections.namedtuple
最简单的构建方式,从
Python 2.6
开始提供。
typing.NamedTuple
另一种构建方式,需要为字段添加类型提示,从
Python 3.5
开始提供。
class
句法在
Python 3.6
中增加。
@dataclasses.dataclass
一个类装饰器,与前两种方式相比,可定制的内容更多,增加了大量选项,可实现更复
杂的功能,从
Python 3.7
开始提供。
介绍这些类构建器之后,接下来将讨论为什么
数据类
模式也是一种代码异味,它的出现可
能意味着面向对象设计欠佳。
1
《重构:改善既有代码的设计》(后面简称《重构》),第
3
章,
3.20
节。
124
5
typing.TypedDict
typing.NamedTuple
句法相似,而且在
Python ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Python高级编程(第2版)

Python高级编程(第2版)

Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
Python贝叶斯分析(第2版)

Python贝叶斯分析(第2版)

Posts & Telecom Press, Osvaldo Martin
高效能PYTHON程式設計

高效能PYTHON程式設計

Micha Gorelick, Ian Ozsvald

Publisher Resources

ISBN: 9787115612366