- Mastering Objectoriented Python
- Steven F. Lott
- 293字
- 2021-11-12 16:25:11
Chapter 3. Attribute Access, Properties, and Descriptors
An object is a collection of features, including methods and attributes. The default behavior of the object
class involves setting, getting, and deleting named attributes. We often need to modify this behavior to change the attributes available in an object.
This chapter will focus on the following five tiers of attribute access:
- We'll look at built-in attribute processing, which is the simplest, but least sophisticated option.
- We'll review the
@property
decorator. A property extends the concept of an attribute to include the processing defined in method functions. - We'll look at how to make use of the lower-level special methods that control attribute access:
__getattr__()
,__setattr__()
, and__delattr__()
. These special methods allow us to build more sophisticated attribute processing. - We'll also take a look at the
__getattribute__()
method, which provides more granular control over attributes. This can allow us to write very unusual attribute handling. - Finally, we'll take a look at descriptors. These are used to access an attribute, but they involve somewhat more complex design decisions. Descriptors are used heavily by Python under the hood to implement properties, static methods, and class methods.
In this chapter, we'll see how the default processing works in detail. We need to decide where and when to override the default behavior. In some cases, we want our attributes to do more than simply be instance variables. In other cases, we might want to prevent adding attributes. We may have attributes that have even more complex behaviors.
Also, as we explore descriptors, we'll come to a much deeper understanding of how Python's internals work. We don't often need to use descriptors explicitly. We often use them implicitly, however, because they're the mechanism that implements a number of Python features.