如何正確地使用Python的屬性和描述符

發表於2016-08-22

關於@property裝飾器

在Python中我們使用@property裝飾器來把對函式的呼叫偽裝成對屬性的訪問。

那麼為什麼要這樣做呢?因為@property讓我們將自定義的程式碼同變數的訪問/設定聯絡在了一起,同時為你的類保持一個簡單的訪問屬性的介面。

舉個例子,假如我們有一個需要表示電影的類:

你開始在專案的其他地方使用這個類,但是之後你意識到:如果不小心給電影打了負分怎麼辦?你覺得這是錯誤的行為,希望Movie類可以阻止這個錯誤。 你首先想到的辦法是將Movie類修改為這樣:

但這行不通。因為其他部分的程式碼都是直接通過Movie.score來賦值的。這個新修改的類只會在__init__方法中捕獲錯誤的資料,但對於已經存在的類例項就無能為力了。如果有人試著執行m.scrore= -100,那麼誰也沒法阻止。那該怎麼辦?

Python的property解決了這個問題。

我們可以這樣做

這樣在任何地方修改score都會檢測它是否小於0。

property的不足

對property來說,最大的缺點就是它們不能重複使用。舉個例子,假設你想為ticket欄位也新增非負檢查。下面是修改過的新類:

可以看到程式碼增加了不少,但重複的邏輯也出現了不少。雖然property可以讓類從外部看起來介面整潔漂亮,但是卻做不到內部同樣整潔漂亮。

描述符登場

什麼是描述符?

一般來說,描述符是一個具有繫結行為的物件屬性,其屬性的訪問被描述符協議方法覆寫。這些方法是__get__()、__set__()和__delete__(),一個物件中只要包含了這三個方法中的至少一個就稱它為描述符。

描述符有什麼作用?

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting witha.__dict__[‘x’], then type(a).__dict__[‘x’], and continuing through the base classes of type(a) excluding metaclasses. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.—–摘自官方文件

簡單的說描述符會改變一個屬性的基本的獲取、設定和刪除方式。

先看如何用描述符來解決上面 property邏輯重複的問題。

因為描述符優先順序高並且會改變預設的get、set行為,這樣一來,當我們訪問或者設定Movie().score的時候都會受到描述符Integer的限制。

不過我們也總不能用下面這樣的方式來建立例項。

a = Movie()
a.score = 1
a.ticket = 2
a.title = ‘test’
a.descript = ‘…’

這樣太生硬了,所以我們還缺一個建構函式。

這樣在獲取、設定和刪除score和ticket的時候都會進入Integer的__get__、__set__,從而減少了重複的邏輯。

現在雖然問題得到了解決,但是你可能會好奇這個描述符到底是如何工作的。具體來說,在__init__函式裡訪問的是自己的self.score和self.ticket,怎麼和類屬性score和ticket關聯起來的?

描述符如何工作

看官方的說明

If an object defines both __get__() and __set__(), it is considered a data descriptor. Descriptors that only define __get__() are called non-data descriptors (they are typically used for methods but other uses are possible).

Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.

The important points to remember are:

descriptors are invoked by the __getattribute__() method
overriding __getattribute__() prevents automatic descriptor calls
object.__getattribute__() and type.__getattribute__() make different calls to __get__().
data descriptors always override instance dictionaries.
non-data descriptors may be overridden by instance dictionaries.
類呼叫__getattribute__()的時候大概是下面這樣子:

 

下面是摘自國外一篇部落格上的內容。

Given a Class “C” and an Instance “c” where “c = C(…)”, calling “c.name” means looking up an Attribute “name” on the Instance “c” like this:

Get the Class from Instance
Call the Class’s special method getattribute__. All objects have a default __getattribute
Inside getattribute

Get the Class’s mro as ClassParents
For each ClassParent in ClassParents
If the Attribute is in the ClassParent’s dict
If is a data descriptor
Return the result from calling the data descriptor’s special method __get__()
Break the for each (do not continue searching the same Attribute any further)
If the Attribute is in Instance’s dict
Return the value as it is (even if the value is a data descriptor)
For each ClassParent in ClassParents
If the Attribute is in the ClassParent’s dict
If is a non-data descriptor
Return the result from calling the non-data descriptor’s special method __get__()
If it is NOT a descriptor
Return the value
If Class has the special method getattr
Return the result from calling the Class’s special method__getattr__.
我對上面的理解是,訪問一個例項的屬性的時候是先遍歷它和它的父類,尋找它們的__dict__裡是否有同名的data descriptor如果有,就用這個data descriptor代理該屬性,如果沒有再尋找該例項自身的__dict__,如果有就返回。任然沒有再查詢它和它父類裡的non-data descriptor,最後查詢是否有__getattr__

描述符的應用場景

python的property、classmethod修飾器本身也是一個描述符,甚至普通的函式也是描述符(non-data discriptor)

django model和SQLAlchemy裡也有描述符的應用

後記

只有當確實需要在訪問屬性的時候完成一些額外的處理任務時,才應該使用property。不然程式碼反而會變得更加囉嗦,而且這樣會讓程式變慢很多。

參考文章:

https://docs.python.org/3.5/h…

http://www.betterprogramming….

http://stackoverflow.com/ques…

http://www.jianshu.com/p/250f…

http://www.geekfan.net/7862/

相關文章