Python描述器

在python中一个描述器就是定义下面的方法中一个或多个的一个对象:

__get__(self, instance, owner)t
__set__(self, instance, value)
__delete__(self, instance)

如果一个对象同时定义了__get__()__set__(),它叫做资料描述器。只定义了__get__()的描述器叫做非资料描述器(一般用于方法)。 资料描述器和非资料描述器的区别在于:相对于实例字典的优先级。如果实例字典中有与资料描述器同名的属性,优先使用资料描述器中的;如果实例字典中有与非资料描述器中同名的属性,优先使用实例字典中的。即优先级 资料描述器 > 实例字典 > 非资料描述器。
要想写一个只读的资料描述器,只需同时定义__get__()__set__()并在__set__()中抛出一个AttributeError

描述器的调用
描述器可以直接这么调用:descriptor.__get__(obj),不过一般都是用来拦截对实例属性的访问。
描述器的调用规则如下:

  • __get__(self, instance, owner)
  obj.descriptor         will call descriptor.__get__(obj. OwnerClass)
  OwnerClass.descriptor  will call  descriptor.__get__(None, OwnerClass)
  • __set__(self, instance, value)
  obj.descriptor = 5     will call  descriptor.__set__(obj, 5)
  • __delete__(self, instance)
  del obj.descriptor     will call  descriptor.__delete__(obj)

参考资料:
Python Gossip: 描述器
Python描述器引导
Descriptor HowTo Guide
Python descriptor
Python FAQ: Descriptors

原文地址:https://www.cnblogs.com/arcticant/p/4593371.html