描述符详解

初学py的时候你们都说描述符是高级内容难度较大,仔细撸过文档以后感受还好,不过用起来确实不那么直观。html

按照惯例,先来看一下官文API文档:python

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: __get__(), __set__(), and __delete__().
If any of those methods are defined for an object, it is said to be a descriptor.

总的来讲,描述符是一个带有绑定行为的对象属性,访问这个对象属性的时候会被描述符协议中的方法覆盖,能够理解为一种hook机制。app

The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class.
the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents.

描述符协议包括三个魔术方法:less

  • object.__get__(self, instance, owner):经过owner class或其实例访问描述符实例时被调用。
  • object.__set__(self, instance, value):给owner class的中的描述符实例赋值的时候被调用。
  • object.__delete__(self, instance):删除owner class中的描述符实例的时候被调用,这个方法不多用。

一个对象只要实现其中之一就是一个描述符。
描述符必须在owner class或者其父类的属性字典中,也就是owner的类属性,定义成实例属性无效。ide

For instance bindings, the precedence of descriptor invocation depends on the which descriptor methods are defined.
A descriptor can define any combination of __get__(), __set__() and __delete__().
If it does not define __get__(), then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary.
If the descriptor defines __set__() and/or __delete__(), it is a data descriptor. 
if it defines neither, it is a non-data descriptor. 

Normally, data descriptors define both __get__() and __set__(), while non-data descriptors have just the __get__() method.
Data descriptors with __set__() and __get__() defined always override a redefinition in an instance dictionary.
In contrast, non-data descriptors can be overridden by instances.

若是描述符class中没有定义__get__()方法,那么访问描述符实例仅仅会返回一个描述符class的实例,而不会触发调用。
若是定义了__set__()和__delete__ ()其中之一就是一个数据描述符
若是都没有定义,即只定义__get__,那么就是一个非数据描述符code

一般,数据描述符会同时定义__get__()和__set__(),非数据描述符仅定义__get__()。orm

其实,基础概念看到这里就能够了,弄清何时触发__get__()、何时触发__set__()便可。
至于描述符实例啥时候会被覆盖这一点常常会把萌新弄晕,并且这一点属于面向对象基础知识,跟描述符自己无关。htm


下面举两个例子简单看一下非数据描述符和数据描述符。对象

非数据描述符:ip

class A:
    def __init__(self):
        self.a = 'a'
        print('A init')

    def __get__(self, instance, owner):
        print('A.__get__ {} {} {}'.format(self, instance, owner))
        return self

class B:
    x = A()
    def __init__(self):
        self.b = 'b'  # 这个仅仅是一个实例属性,与描述符无关
        # self.x = 'x'   # 因为描述符没有定义__set__方法,这里不能这样定义,实例化的时候实例属性会覆盖类属性,描述符将被覆盖
        print('B init')

print(B.x)  # 这里会调用A的__get__方法,返回的是__get__方法的返回值
# A init
# A.__get__ <__main__.A object at 0x10302d5c0> None <class '__main__.B'>
# <__main__.A object at 0x10302d5c0>

b = B()
print(b.x)  # 这里也会调用A的__get__方法,不过这里会把b实例传递进去
# B init
# A.__get__ <__main__.A object at 0x10302d5c0> <__main__.B object at 0x10302d748> <class '__main__.B'>
# <__main__.A object at 0x10302d5c0>

# 为了可以获取描述符实例的属性,可让__get__方法返回self
print(b.x.a)
# A.__get__ <__main__.A object at 0x10302d5c0> <__main__.B object at 0x10302d748> <class '__main__.B'>
# a

print(b.b)
# b

数据描述符:

class A:
    def __init__(self):
        self.a = 'a'
        print('A init')

    def __get__(self, instance, owner):
        print('A.__get__ {} {} {}'.format(self, instance, owner))
        return self

    def __set__(self, instance, value):
        print('A.__set__ {} {} {}'.format(self, instance, value))
        instance.c = value

class B:
    x = A()
    def __init__(self):
        self.b = 'b'
        self.x = 'c'    # 因为描述符定义了__set__方法,这里对描述符实例的赋值操做会调用描述符的__set__方法,并无覆盖描述符
        print('B init')

b = B()
print(b.__dict__)
# {'b': 'b', 'c': 'c'}

b.x = 100
print(b.__dict__)
# {'b': 'b', 'c': 100}

因为涉及两个类和其实例的交互,阐述起来也不是很容易呢。不过仔细捋一下,其实并非很复杂,有没有?


最后,须要提醒一下,staticmethod、classmethod、property三个内置装饰器都是经过描述符实现的。
其中,staticmethod和classmethod是经过非数据描述符实现的,property是经过数据描述符实现的。

Python methods (including staticmethod() and classmethod()) are implemented as non-data descriptors.
The property() function is implemented as a data descriptor.

一般你们知道怎么用这几个装饰器,但每每可能不会细究是如何实现的,下篇继续来讲这几个装饰器是如何实现的。

参考:
https://docs.python.org/3/reference/datamodel.html#implementing-descriptors
https://docs.python.org/3/reference/datamodel.html#invoking-descriptors

相关文章
相关标签/搜索