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版)
279
11
符合
Python
风格的对象
一个库或框架是否符合
Python
风格,要看它能不能让
Python
程序员以一种简单
而自然的方式执行任务。
——
Martijn Faassen
Python
JavaScript
框架开发者
1
得益于
Python
数据模型,自定义类型的行为可以像内置类型那样自然。实现如此自然的行
为,靠的不是继承,而是
鸭子类型
:只需按照预定行为实现对象所需的方法即可。
前几章分析了很多内置对象的行为。本章会自己定义类,让类的行为跟真正的
Python
对象
一样。你在开发应用程序时,不一定要像本章的示例那样实现那么多特殊方法。然而,对
库或框架来说,程序员可能希望你定义的类能像
Python
内置的类一样
。满足这个预期也算
得上是符合“
Python
风格”
本章接续第
1
章,说明如何实现很多
Python
类型中常见的特殊方法。
本章包含以下话题:
把对象转换成其他类型的内置函数(例如
repr()
bytes()
complex()
);
通过一个类方法实现备选构造函数;
扩展
f
字符串、内置函数
format()
str.format()
方法使用的格式化微语言;
实现只读属性;
把对象变为可哈希的,以便在集合中及作为
dict
的键使用;
利用
__slots__
节省内存。
本章将开发一个简单的二维欧几里得向量类型
Vector2d
,在这个过程中涵盖上述全部话
1
摘自
Faassen
的题为“
What is Pythonic?
”的博客文章。
280
11
题。
Vector2d
将为第
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