Learning Python, 5th Edition - cdn.oreilly.com
Learning Python, 5th Edition - cdn.oreilly.com
Learning Python, 5th Edition - cdn.oreilly.com
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
38. Managed Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1219<br />
Why Manage Attributes? 1219<br />
Inserting Code to Run on Attribute Access 1220<br />
Properties 1221<br />
The Basics 1222<br />
A First Example 1222<br />
Computed Attributes 1224<br />
Coding Properties with Decorators 1224<br />
Descriptors 1226<br />
The Basics 1227<br />
A First Example 1229<br />
Computed Attributes 1231<br />
Using State Information in Descriptors 1232<br />
How Properties and Descriptors Relate 1236<br />
__getattr__ and __getattribute__ 1237<br />
The Basics 1238<br />
A First Example 1241<br />
Computed Attributes 1243<br />
__getattr__ and __getattribute__ Compared 1245<br />
Management Techniques Compared 1246<br />
Intercepting Built-in Operation Attributes 1249<br />
Example: Attribute Validations 1256<br />
Using Properties to Validate 1256<br />
Using Descriptors to Validate 1259<br />
Using __getattr__ to Validate 1263<br />
Using __getattribute__ to Validate 1265<br />
Chapter Summary 1266<br />
Test Your Knowledge: Quiz 1266<br />
Test Your Knowledge: Answers 1267<br />
39. Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1269<br />
What’s a Decorator? 1269<br />
Managing Calls and Instances 1270<br />
Managing Functions and Classes 1270<br />
Using and Defining Decorators 1271<br />
Why Decorators? 1271<br />
The Basics 1273<br />
Function Decorators 1273<br />
Class Decorators 1277<br />
Decorator Nesting 1279<br />
Decorator Arguments 1281<br />
Decorators Manage Functions and Classes, Too 1282<br />
Coding Function Decorators 1283<br />
xxviii | Table of Contents