歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python中descriptor(描述器)

Python中descriptor(描述器)

日期:2017/3/1 9:38:49   编辑:Linux編程

很多教程往往把Python中descriptor說的很復雜,長篇大文,洋洋灑灑,結果很多人看的雲裡霧裡。

其實就一句話,對類的操作進行hook,以此控制行為.

大部分時候是用來攔截對實例屬性的訪問。
只要類中有__get__(), __set__(), 和 __delete__()其中之一的方法.那麼它就是一個描述器.我們想一想,對一個類進行操作,逃不開這三種方法,我們需要控制什麼操作,就hook哪個方法.
描述器不是self host的,而是寄生在其它類中.
property, classmethod, staticmethod, super的實現原理正是描述器.

說這麼多,下面用代碼展示,相信一清二楚.

#coding=utf-8
class Integer(object):#Integer就是一個描述器,因為定義了__set__()方法.
def __init__(self, name):
self.name = name
def __set__(self, instance, value):#因為我們只需要對"修改屬性"這個行為進行hook,所以我們只定義__set__()方法就夠了,不用__get__()和__delete__().
if not isinstance(value, int):
raise TypeError('Expected an int')
instance.__dict__[self.name] = value

class Point(object):
x = Integer('x')
y = Integer('y')
def __init__(self, x, y):
self.x = x
self.y = y

p = Point(2, 3)
p.x = 9
p.x = 9.9#這句會拋出TypeError: Expected an int錯誤.這就是描述器的作用。

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved