Skip to content

Latest commit

 

History

History
executable file
·
24 lines (14 loc) · 2.92 KB

20章-属性描述符.md

File metadata and controls

executable file
·
24 lines (14 loc) · 2.92 KB

CHAPTER 20 Attribute descriptors

Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python works and an appreciation for the elegance of its design [1] — Raymond Hettinger Python core developer and guru

[1]: 1. Reymond Hettinger, Descriptor HowTo Guide.

Descriptors are a way of reusing the same access logic in multiple attributes. For ex‐ ample, field types in ORMs such as the Django ORM and SQL Alchemy are descriptors, managing the flow of data from the fields in a database record to Python object attributes and vice-versa.

描述符是一种在多属性的环境中重复使用相同访问逻辑的方法。例如,像Django ORM 和SQLAlchemy这些ORM中的字段类型都是描述符,这些描述符管理者数据库中字段的记录Python对象属性的数据流,反之亦然。

A descriptor is a class which implements a protocol consisting of the __get__, __set__ and __delete__ methods. The property class implements the full descriptor protocol. As usual with protocols, partial implementations are OK. In fact, most descriptors we see in real code implement only __get__ and__set__, and many implement only one of these methods.

描述符是一个实现了由 __get__, __set__ and __delete__ 方法组成的协议。property类实现了完整的描述符协议。通常使用协议,部分地实现是没有问题的。事实上,我们在现实世界中见到的代码中的很多的描述符仅由 __get____set__ 实现,而且很多的实现也只有这两个方法中的一个。

Descriptors are a distinguishing feature of Python, deployed not only at the application level but also in the language infrastructure. Besides properties, other Python features that leverage descriptors are methods and the classmethod and staticmethod deco‐ rators. Understanding descriptors is key to Python mastery. This is what this chapter is about.

描述符是Python独有的功能,它不仅被部署在了应用层面而且也存在于这门语言的基础部分。除了特性,对描述符还有影响的方法是classmethod 和 staticmethod装饰器。理解描述符是精通Python的关键所在。这也是本章将要详细说明的。

Descriptor example: attribute validation

As we saw in “Coding a property factory” on page 613, a property factory is a way to avoid repetitive coding of getters and setters by applying functional programming pat‐ terns. A property factory is a higher-order function that creates a parametrized set of accessor functions and builds a custom property instance from them, with closures to hold settings like the storage_name. The object oriented way of solving the same prob‐ lem is a descriptor class.
We’ll continue the series of LineItem examples where we left it, in “Coding a property factory” on page 613, by refactoring the quantity property factory into a Quantity descriptor class.