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版)
232
9
装饰器和闭包
有很多人抱怨,把这个功能命名为“装饰器”不好。主要原因是,这个名称与
《设计模式:可复用面向对象软件的基础》(后面简称《设计模式》)中使用的不一
致。
装饰器
这个名称可能更适合在编译器领域使用,因为它会遍历并注解句法树。
——“
PEP
318
Decorators for Functions and Methods
函数装饰器允许在源码中“标记”函数,以某种方式增强函数的行为。这是一个强大的功
能,但是如果想掌握,则必须理解闭包,即捕获函数主体外部定义的变量。
Python 3.0
引入的保留关键字
nonlocal
鲜为人知。作为
Python
程序员,如果严格遵守基于
类的面向对象编程方式,那么即便不知道它的存在也不受影响。然而,如果想自己实现函
数装饰器,则必须了解闭包的方方面面,因此也就需要掌握
nonlocal
除了在装饰器中有用,闭包还是回调式编程和函数式编程风格的重要基础。
本章的最终目标是解释清楚函数装饰器的工作原理,从最简单的注册装饰器开始,一直讲
到较为复杂的参数化装饰器。然而,在实现这一目标之前,需要讨论以下话题:
Python
如何求解装饰器句法;
Python
如何判断变量是不是局部的;
闭包存在的原因和工作原理;
nonlocal
能解决什么问题。
掌握这些基础知识后,可以再进一步探讨装饰器:
实现行为良好的装饰器;
标准库中强大的装饰器:
@cache
@lru_cache
@singledispatch
实现一个参数化装饰器。
装饰器和闭包 ...
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