Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

一文看懂 Python 中的 descriptor(描述器)

很多教程往往把 Python 中的 descriptor 講得又複雜又冗長,結果讀者看完仍是雲裡霧裡。

其實一句話就能概括:對類的操作進行 hook,以此控制行為。

大多數時候,它用來攔截對實例屬性的訪問。
只要類中定義了 __get__()、__set__() 和 __delete__() 三者之一,它就是一個描述器。想一想,對一個類進行操作,逃不開這三種方法,我們需要控制哪種操作,就 hook 哪個方法。
描述器不是自托管的,而是寄生在其他類中。
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 中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm

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

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

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

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

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

Copyright © Linux教程網 All Rights Reserved