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版)
695
24
类元编程
所有人都知道调试程序的难度是写程序的两倍。所以如果你写程序的时候尽可能
地“精明”,那么未来将如何调试它?
——
Brian W
. Kernighan
P. J. Plauger
《编程格调》
类元编程指在运行时创建或定制类的技艺。在
Python
,类是一等对象,因此任何时候都
可以使用函数新建类,无须使用
class
关键字。类装饰器也是函数,不过能够审查、修改,
甚至把被装饰的类替换成另一个类。最后,元类是类元编程最高级的工具:使用元类可以
创建具有某种特质的全新类,例如前面讲过的抽象基类。
元类功能强大,但是难以掌握。类装饰器能使用更简单的方式解决很多同类问题。此外,
Python 3.6
实现的“
PEP
487
Simpler customization of class creation
”提供了一些特殊方法,
可以完成以前需要元类或类装饰器才能完成的任务。
1
本章按照复杂度从易到难讲解类元编程技术。
这是一个令人兴奋的话题,很容易让人忘乎所以。因此,我必须提出以下
警告。
为了可读性和可维护性,或许应该避免在应用程序代码中使用本章讲解的
技术。
反之,如果想编写下一个引起轰动的
Python
框架
,那么肯定离不开这些
工具。
1
并不是说
PEP 487
会破坏使用那些功能的代码。只是在
Python 3.6
以前使用类装饰器或元类编写的
代码,现在可以使用普通的类重构,写出的代码更简单且更高效。
696
24
24.1
 本章新增内容
本书第
1
版“类元编程”一章中的所有代码依然能正常运行。然而,与 ...
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