1、什么是描述符?

描述符是Python新式类的关键点之一,它为对象属性提供强大的API,你可以认为描述符是表示对象属性的一个代理。当需要属性时,可根据你遇到的情况,通过描述符进行访问他(摘自Python核心编程)。

 

2、描述符及其相关属性的简单定义

2.0 属性:__dict__

作用:字典类型,存放本对象的属性,key(键)即为属性名,value(值)即为属性的值,形式为{attr_key : attr_value}。
__dict__是对象的默认属性,所以每个类对象和实例化对象都有这个属性。

对象属性的访问顺序:

(1)实例对象/类对象的属于描述符的属性

(2)实例属性

(3)类属性

(3)父类属性

(4)__getattr__()方法

2.1 魔法方法__get__(), __getattr__(), __getattribute__()

作用:查找类对象或者实例对象的属性(也就是用于获取对象的__dict__属性中的值)

这三个魔法方法的调用顺序如下:

如果 obj = Clz(), 那么obj.attr 顺序如下:

(1)如果“attr”是出现在Clz或其父类的__dict__中, 且attr是data descriptor, 那么调用其__get__方法, 否则

(2)如果“attr”出现在obj的__dict__中, 那么直接返回 obj.__dict__['attr'], 否则

(3)如果“attr”出现在Clz或其父类的__dict__中

(3.1)如果attr是non-data descriptor,那么调用其__get__方法, 否则

(3.2)返回 __dict__['attr']

(4)如果Clz有__getattr__方法,调用__getattr__方法,否则

(5)抛出AttributeError

实际上还是上面那个调用顺序。只是结合描述符进行了一些补充关于描述符的补充

2.2 魔法方法:__get__(), __set__(), __delete__() 与descriptor 的简单定义

描述符本质上是一个类属性,实现描述符的类被称为描述符类。

其中只实现了__set__()方法的被当做方法描述符,或者是非数据描述符。

那些同时实现了__set__()__get__()方法的类被称作数据描述符。

而魔法方法__get__(), __set__(), __delete__() 就用于定义和调用类属性 __dict__

  1. __get__(self, object, type) # 用于得到一个属性的值
  2. __set__(self, obj, val) # 用于为一个属性赋值
  3. __delete__(self, obj) # 删除某个属性时被调用,但很少用到

 

2.3 描述符的定义和调用初体验

  1. # 描述符类的定义
  2. class MyDescriptor(object):
  3. def __init__(self, value):
  4. self.value = value
  5.  
  6. # 描述符value的访问
  7. def __get__(self, instance, owner):
  8. return self.value
  9.  
  10. # 描述符value的定义
  11. def __set__(self, instance, value):
  12. self.value = value
  13.  
  14. class MyClass(object):
  15.  
  16.   mydescriptor = MyDescriptor(5)
  17.    # 在MyClass类中创建一个描述符mydescriptor,重申一下,这是一个类属性。
  18. # #同时可以看到,mydescriptor不仅仅是MyClass类的一个类属性,同时还是MyDescriptor的一个实例对象。
  19. # #这样就将一个类的类属性定义成了另一个类的实例对象。
  20.  
  21. if __name__ == '__main__':
  22. print (MyClass.mydescriptor) # 输出为 5

发现访问 MyClass 的 mydescriptor 属性时,调用了描述符的__get__()方法,访问了描述符类的实例属性value

这就达到了描述符的作用:可以改变了类对象属性的访问。

调用原理:对于类属性描述符,如果解析器发现属性x是一个描述符的话,在内部通过type.__getattribute__()(访问属性时无条件调用,最先调用),它能把Class.x转换成Class.__dict__[‘x’].__get__(None, Class)来访问

 

3、魔法方法:__get__(), __set__(), __delete__() 和 descriptor

上面简单说了几个定义,接下来我们来解决一些实际使用中的细节问题。

1) 首先我们先看一段代码:

  1. class Test(object):
  2. cls_val = 1
  3. def __init__(self):
  4. self.ins_val = 10
  5.  
  6. >>> t=Test()
  7.  
  8. >>> Test.__dict__
  9. mappingproxy({'__module__': '__main__', 'cls_val': 1, '__init__': <function Test.__init__ at 0x0000000002E35D08>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None})
  10.  
  11. >>> t.__dict__
  12. {'ins_val': 10}
  13.  
  14. # 更改实例t的属性cls_val,只是新增了一个实例属性,并不影响类Test的类属性cls_val
  15. >>> t.cls_val = 20
  16.  
  17. >>> t.__dict__
  18. {'ins_val': 10, 'cls_val': 20}
  19.  
  20. >>> Test.__dict__
  21. mappingproxy({'__module__': '__main__', 'cls_val': 1, '__init__': <function Test.__init__ at 0x0000000002E35D08>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None})
  22.  
  23. # 更改了类Test的属性cls_val的值,由于事先增加了实例t的cls_val属性,因此不会改变实例的cls_val值
  24. >>> Test.cls_val = 30
  25.  
  26. >>> t.__dict__
  27. {'ins_val': 10, 'cls_val': 20}
  28.  
  29. >>> Test.__dict__
  30. mappingproxy({'__module__': '__main__', 'cls_val': 30, '__init__': <function Test.__init__ at 0x0000000002E35D08>, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None})

以上这段代码证明:

在实例化对象时,类属性并不被实例继承。只有__init__()函数中的self.属性 也就是实例属性可以被继承。

在实例化结束之后,类属性和实例属性互不影响。

2) 下面我们仔细看看__get__()方法的调用过程

  1. class Desc(object):
  2. def __init__(self, value):
  3. self.value = value
  4.  
  5. def __get__(self, instance, owner):
  6. print("...__get__...")
  7. print("self : \t\t", self)
  8. print("instance : \t", instance)
  9. print("owner : \t", owner)
  10. print('-'*40)
  11. return self.value
  12.  
  13. def __set__(self, instance, value):
  14. print('...__set__...')
  15. print("self : \t\t", self)
  16. print("instance : \t", instance)
  17. print("value : \t", value)
  18. print('-'*40)
  19. self.value = value
  20.  
  21. class TestDesc(object):
  22. desc = Desc(666)
  23.  
  24. # 以下为测试代码
  25. testdesc = TestDesc()
  26.  
  27. print('testdesc.desc:%s' %testdesc.desc)
  28. print('='*40)
  29. print('TestDesc.desc:%s' %TestDesc.desc)
  30.  
  31. # 以下为输出结果
  32. ...__get__...
  33. self : <__main__.Desc object at 0x00000238491959B0>
  34. instance : <__main__.TestDesc object at 0x000002384AFECD68>
  35. owner : <class '__main__.TestDesc'>
  36. ----------------------------------------
  37. testdesc.desc:666
  38. ========================================
  39. ...__get__...
  40. self : <__main__.Desc object at 0x00000238491959B0>
  41. instance : None
  42. owner : <class '__main__.TestDesc'>
  43. ----------------------------------------
  44. TestDesc.desc:666

以上代码说明:

1. 调用实例属性和调用类属性的是同一个对象,实际上他们都是由描述符类调用的。

2. 不管是类对象的类属性还是实例对象的实例属性  其实际属性都是描述符的类属性。

3. 被描述的类属性在被实例化时是被实例对象继承的。示例中testdesc.desc和TestDesc.desc有相同的值,而且是实例化之前的值。

3) 描述符是不能定义成实例属性的

  1. # coding=utf-8
  2. class Descriptor(object):
  3. def __init__(self, value):
  4. self.value = value
  5.  
  6. def __get__(self, instance, owner):
  7. print ("访问属性")
  8. return self.value
  9.  
  10. def __set__(self, instance, value):
  11. print ("设置属性值")
  12. self.value = value
  13.  
  14. class TestDesc(object):
  15. classdesc = Descriptor(888)
  16.  
  17. def __init__(self):
  18. self.insdesc = Descriptor(666)
  19.  
  20. # 以下为测试代码
  21. testdesc = TestDesc()
  22. print(TestDesc.classdesc)
  23. print(testdesc.classdesc)
  24. print(testdesc.insdesc)
  25.  
  26. # 以下为输出结果
  27. 访问属性
  28. 888
  29. 访问属性
  30. 888
  31. <__main__.Descriptor object at 0x0000025041A64940>

可以看到,实例对象testdesc的 实例属性insdesc 并没有调用__get__()方法,只是说他是一个Descriptor对象。

这是因为当访问实例描述符对象时,obj.__getattribute__()会将myclass.desc转换为type(myclass).__dict__['desc'].__get__(myclass, type(myclass)),即到类属性中去寻找desc,并调用他的__get__()方法。而Myclass类中没有desc属性,所以无法访调用到__get__方法.
描述符是一个类属性,必须定义在类的层次上, 而不能单纯的定义为对象属性。

4. python的property方法

通过使用 property(),可以轻松地为任意属性创建可用的描述符。

property内建函数有四个参数:property(fget=None, fset=None, fdel=None, doc=None)

这四个参数都接受函数类型

  1. class PropertyDesc(object):
  2. def __init__(self):
  3. self.__name = ''
  4.  
  5. def fget(self):
  6. print ("Getting: %s" % self.__name)
  7. return self.__name
  8.  
  9. def fset(self, value):
  10. self.__name = value
  11. print ("Setting: %s" % value)
  12.  
  13. def fdel(self):
  14. print ("Deleting: %s" % self.__name)
  15. del self.__name
  16.  
  17. name = property(fget, fset, fdel, "I'm the property.")
  18.  
  19. if __name__ == '__main__':
  20. pro = PropertyDesc()
  21. pro.name = "hellokitty"
  22. print(pro.name)
  23. del pro.name
  24.  
  25. # 以下为输出结果
  26. Setting: hellokitty
  27. Getting: hellokitty
  28. hellokitty
  29. Deleting: hellokitty

当然也可以使用装饰器的方式实现以上内容:

  1. class PropertyDesc(object):
  2. def __init__(self):
  3. self._name = ''
  4.  
  5. @property
  6. def name(self):
  7. print ("Getting: %s" % self._name)
  8. return self._name
  9.  
  10. @name.setter
  11. def name(self, value):
  12. print ("Setting: %s" % value)
  13. self._name = value
  14.  
  15. @name.deleter
  16. def name(self):
  17. print ("Deleting: %s" %self._name)
  18. del self._name
  19.  
  20. if __name__ == '__main__':
  21. pro = PropertyDesc()
  22. pro.name = "hello world"
  23. print(pro.name)
  24. del pro.name
  25.  
  26. # 以下为输出内容
  27. Setting: hello world
  28. Getting: hello world
  29. hello world
  30. Deleting: hello world

Python 描述符 (descriptor)的更多相关文章

  1. Python 描述符(descriptor) 杂记

    转自:https://blog.tonyseek.com/post/notes-about-python-descriptor/ Python 引入的“描述符”(descriptor)语法特性真的很黄 ...

  2. python描述符descriptor(一)

    Python 描述符是一种创建托管属性的方法.每当一个属性被查询时,一个动作就会发生.这个动作默认是get,set或者delete.不过,有时候某个应用可能会有 更多的需求,需要你设计一些更复杂的动作 ...

  3. python描述符 descriptor

    descriptor 在python中,如果一个新式类定义了__get__, __set__, __delete__方法中的一个或者多个,那么称之为descriptor.descriptor通常用来改 ...

  4. python描述符(descriptor)、属性(property)、函数(类)装饰器(decorator )原理实例详解

     1.前言 Python的描述符是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题 ...

  5. Python描述符 (descriptor) 详解

    1.什么是描述符? python描述符是一个“绑定行为”的对象属性,在描述符协议中,它可以通过方法重写属性的访问.这些方法有 __get__(), __set__(), 和__delete__().如 ...

  6. Python 描述符(Descriptor) 附实例

    在 Python 众多原生特性中,描述符可能是最少被自定义的特性之一,但它在底层实现的方法和属性却无时不刻被使用着,它优雅的实现方式体现出 Python 简洁之美. 定义 一个描述符是一个有" ...

  7. python描述符descriptor(二)

    python内置的描述符 python有些内置的描述符对象,property.staticmethod.classmethod,python实现如下: class Property(object): ...

  8. 【python】描述符descriptor

    开始看官方文档,各种看不懂,只看到一句Properties, bound and unbound methods, static methods, and class methods are all ...

  9. 杂项之python描述符协议

    杂项之python描述符协议 本节内容 由来 描述符协议概念 类的静态方法及类方法实现原理 类作为装饰器使用 1. 由来 闲来无事去看了看django中的内置分页方法,发现里面用到了类作为装饰器来使用 ...

随机推荐

  1. webpack3升级webpack4

    cnpm i webpck@4 webpack-cli -D cnpm i webpack-cli -D cnpm update npm WARN deprecated extract-text-we ...

  2. C++入门经典-例4.3-函数的递归调用之汉诺塔问题

    1:代码如下: // 4.3.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> using ...

  3. HashMap如何实现序列化

    /** * Save the state of the <tt>HashMap</tt> instance to a stream (i.e., * serialize it) ...

  4. 查看线程的cpu占用率

    1)         top -H -p 进程pid 查看线程的线程ID与CPU占用情况.或者使用 ps -eLo pid,lwp,pcpu | grep 进程pid2)         pstack ...

  5. java多线程系列3:悲观锁和乐观锁

    1.悲观锁和乐观锁的基本概念 悲观锁: 总是认为当前想要获取的资源存在竞争(很悲观的想法),因此获取资源后会立刻加锁,于是其他线程想要获取该资源的时候就会一直阻塞直到能够获取到锁: 在传统的关系型数据 ...

  6. 全面解读php-运算符

    一.运算符的优先级 二.短路作用 本文为袋鼠学习中的总结,如有转载请注明出处:https://www.cnblogs.com/chrdai/p/11074776.html

  7. shell高级-----正则表达式

    正则表达式概述 正则表达式是一种定义的规则,Linux工具可以用它来过滤文本. 基础正则表达式 纯文本 [root@node1 ~]# echo "this is a cat" | ...

  8. DFA算法以及ios中OC实现DFA

    DFA不同于苹果手机的idfa DFA全称为:Deterministic Finite Automaton,即确定有穷自动机.其特征为:有一个有限状态集合和一些从一个状态通向另一个状态的边,每条边上标 ...

  9. linux新建用户tab无法补全命令

    查看passwd cat /ect/passwd 发现root用户的shell是/bin/bash 普通用户的shell是/bin/sh 修改普通用户的为/bin/bash即可

  10. go-ethereum开发问题

    1. abigen 参考文档(Native DApps: Go bindings to Ethereum contracts) abigen --sol token.sol --pkg token - ...