Python黑魔法Descriptor描述符的实例解析
在Python中,访问一个属性的优先级顺序按照如下顺序: def __getattr(self,attr) :#attr是self的一个属性名 pass; 先来阐述下什么叫数据描述符。 数据描述符是指实现了__get__,__set__,__del__方法的类属性(由于Python中,一切皆是对象,所以你不妨把所有的属性也看成是对象) PS:个人觉得这里最好把数据描述符等效于定义了__get__,__del__三个方法的接口。 __get__,__del__ type(x).__dict__['foo'].__get__(x,type(x)) 调用X.foo,等效于调用: type(x).__dict__['foo'].__get__(None,type(x)) class A(object): foo=1.3; print str(A.__dict__); 输出: {'__dict__': <attribute '__dict__' of 'A' objects>,'__module__': '__main__','foo': 1.3,'__weakref__': <attribute '__weakref__' of 'A' objects>,'__doc__': None} 从上图可以看出foo属性在类的__dict__属性里,所以这里用A.foo可以直接找到。这里我们先跨过数据描述符,直接来看实例属性. class A(object): foo=1.3; a=A(); print a.foo; a.foo=15; print a.foo; 这里a.foo先输出1.3后输出15,不是说类属性的优先级比实例属性的优先级高吗?按理a.foo应该不变才对?其实,这里只是一个假象,真正的原因在于这里将a.foo这个引用对象,不妨将其理解为可以指向任意数据类型的指针,指向了15这个int对象。 class A(object): foo=1.3; a=A(); print a.foo; a.foo=15; print a.foo; del a.foo; print a.foo; 这次在输出1.3,15后最后一次又一次的输出了1.3,原因在于a.foo最后一次又按照优先级顺序直接找到了类属性A.foo
class PythonSite(object): webframework = WebFramework() version = 0.01 def __init__(self,site): self.site = site 这里增加了一个version的类属性,以及一个实例属性site。分别查看一下类和实例对象的属性: In [1]: pysite = PythonSite('ghost') In [2]: vars(PythonSite).items() Out[2]: [('__module__','__main__'),('version',0.01),('__dict__',<attribute '__dict__' of 'PythonSite' objects>),('webframework',<__main__.WebFramework at 0x10d55be90>),('__weakref__',<attribute '__weakref__' of 'PythonSite' objects>),('__doc__',None),('__init__',<function __main__.__init__>)] In [3]: vars(pysite) Out[3]: {'site': 'ghost'} In [4]: PythonSite.__dict__ Out[4]: <dictproxy {'__dict__': <attribute '__dict__' of 'PythonSite' objects>,'__doc__': None,'__init__': <function __main__.__init__>,'__weakref__': <attribute '__weakref__' of 'PythonSite' objects>,'version': 0.01,'webframework': <__main__.WebFramework at 0x10d55be90>}> vars方法用于查看对象的属性,等价于对象的__dict__内容。从上面的显示结果,可以看到类PythonSite和实例pysite的属性差别在于前者有 webframework,version两个属性,以及 __init__方法,后者仅有一个site属性。 类与实例的属性 In [6]: pysite1 = PythonSite('ghost') In [7]: pysite2 = PythonSite('admin') In [8]: PythonSite.version Out[8]: 0.01 In [9]: pysite1.version Out[9]: 0.01 In [10]: pysite2.version Out[10]: 0.01 In [11]: pysite1.version is pysite2.version Out[11]: True In [12]: pysite1.version = 'pysite1' In [13]: vars(pysite1) Out[13]: {'site': 'ghost','version': 'pysite1'} In [14]: vars(pysite2) Out[14]: {'site': 'admin'} In [15]: PythonSite.version = 0.02 In [16]: pysite1.version Out[16]: 'pysite1' In [17]: pysite2.version Out[17]: 0.02 正如上面的代码显示,两个实例对象都可以访问version类属性,并且是同一个类属性。当pysite1修改了version,实际上是给自己添加了一个version属性。类属性并没有被改变。当PythonSite改变了version属性的时候,pysite2的该属性也对应被改变。 属性访问的原理与描述器 In [21]: pysite1.site Out[21]: 'ghost' In [22]: pysite1.__dict__['site'] Out[22]: 'ghost' In [23]: pysite2.version Out[23]: 0.02 In [24]: pysite2.__dict__['version'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-24-73ef6aeba259> in <module>() ----> 1 pysite2.__dict__['version'] KeyError: 'version' In [25]: type(pysite2).__dict__['version'] Out[25]: 0.02 In [32]: type(pysite1).__dict__['webframework'] Out[32]: <__main__.WebFramework at 0x103426e90> In [38]: type(pysite1).__dict__['webframework'].__get__(None,PythonSite) Out[38]: 'Flask' 实例方法,类方法,静态方法与描述器 这样说还是比较抽象,下面来分析Python的方法,静态方法和类方法。把PythonSite重构一下: class PythonSite(object): webframework = WebFramework() version = 0.01 def __init__(self,site): self.site = site def get_site(self): return self.site @classmethod def get_version(cls): return cls.version @staticmethod def find_version(): return PythonSite.version 类方法,@classmethod装饰器 In [1]: ps = PythonSite('ghost') In [2]: ps.get_version Out[2]: <bound method type.get_version of <class '__main__.PythonSite'>> In [3]: ps.get_version() Out[3]: 0.01 In [4]: PythonSite.get_version Out[4]: <bound method type.get_version of <class '__main__.PythonSite'>> In [5]: PythonSite.get_version() Out[5]: 0.01 get_version 是一个bound方法。下面再看下ps.get_version这个调用,会先查找它?的__dict__是否有get_version这个属性,如果没有,则查找其类。 In [6]: vars(ps) Out[6]: {'site': 'ghost'} In [7]: type(ps).__dict__['get_version'] Out[7]: <classmethod at 0x108952e18> In [8]: type(ps).__dict__['get_version'].__get__(ps,type(ps)) Out[8]: <bound method type.get_version of <class '__main__.PythonSite'>> In [9]: type(ps).__dict__['get_version'].__get__(ps,type(ps)) == ps.get_version Out[9]: True 并且vars(ps)中,__dict__并没有get_version这个属性,依据描述器协议,将会调用type(ps).__dict__['get_version']描述器的__get__方法,因为ps是实例,因此object.__getattribute__()会这样调用__get__(obj,type(obj))。 现在再看类方法的调用: In [10]: PythonSite.__dict__['get_version'] Out[10]: <classmethod at 0x108952e18> In [11]: PythonSite.__dict__['get_version'].__get__(None,PythonSite) Out[11]: <bound method type.get_version of <class '__main__.PythonSite'>> In [12]: PythonSite.__dict__['get_version'].__get__(None,PythonSite) == PythonSite.get_version Out[12]: True 因为这次调用get_version的是一个类对象,而不是实例对象,因此object.__getattribute__()会这样调用__get__(None,Class)。 静态方法,@staticmethod In [13]: ps.find_version Out[13]: <function __main__.find_version> In [14]: ps.find_version() Out[14]: 0.01 In [15]: vars(ps) Out[15]: {'site': 'ghost'} In [16]: type(ps).__dict__['find_version'] Out[16]: <staticmethod at 0x108952d70> In [17]: type(ps).__dict__['find_version'].__get__(ps,type(ps)) Out[17]: <function __main__.find_version> In [18]: type(ps).__dict__['find_version'].__get__(ps,type(ps)) == ps.find_version Out[18]: True In [19]: PythonSite.find_version() Out[19]: 0.01 In [20]: PythonSite.find_version Out[20]: <function __main__.find_version> In [21]: type(ps).__dict__['find_version'].__get__(None,type(ps)) Out[21]: <function __main__.find_version> In [22]: type(ps).__dict__['find_version'].__get__(None,type(ps)) == PythonSite.find_version Out[22]: True 和类方法差别不大,他们的主要差别是在类方法内部的时候,类方法可以有cls的类引用,静态访问则没有,如果静态方法想使用类变量,只能硬编码类名。 实例方法 In [2]: ps.get_site Out[2]: <bound method PythonSite.get_site of <__main__.PythonSite object at 0x1054ae2d0>> In [3]: ps.get_site() Out[3]: 'ghost' In [4]: type(ps).__dict__['get_site'] Out[4]: <function __main__.get_site> In [5]: type(ps).__dict__['get_site'].__get__(ps,type(ps)) Out[5]: <bound method PythonSite.get_site of <__main__.PythonSite object at 0x1054ae2d0>> In [6]: type(ps).__dict__['get_site'].__get__(ps,type(ps)) == ps.get_site Out[6]: True 一切工作正常,实例方法也是类的一个属性,但是对于类,描述器使其变成了unbound方法: In [7]: PythonSite.get_site Out[7]: <unbound method PythonSite.get_site> In [8]: PythonSite.get_site() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-99c7d7607137> in <module>() ----> 1 PythonSite.get_site() TypeError: unbound method get_site() must be called with PythonSite instance as first argument (got nothing instead) In [9]: PythonSite.get_site(ps) Out[9]: 'ghost' In [10]: PythonSite.__dict__['get_site'] Out[10]: <function __main__.get_site> In [11]: PythonSite.__dict__['get_site'].__get__(None,PythonSite) Out[11]: <unbound method PythonSite.get_site> In [12]: PythonSite.__dict__['get_site'].__get__(None,PythonSite) == PythonSite.get_site Out[12]: True In [14]: PythonSite.__dict__['get_site'].__get__(ps,PythonSite) Out[14]: <bound method PythonSite.get_site of <__main__.PythonSite object at 0x1054ae2d0>> In [15]: PythonSite.__dict__['get_site'].__get__(ps,PythonSite)() Out[15]: 'ghost' 由此可见,类不能直接调用实例方法,除非在描述器手动绑定一个类实例。因为使用类对象调用描述器的时候,__get__的第一个参数是None,想要成功调用,需要把这个参数替换为实例ps,这个过程就是对方法的bound过程。
class simpleDescriptor(object): def __get__(self,type=None) : pass; def __set__(self,val): pass; def __del__(self,obj): pass class A(object): foo=simpleDescriptor(); print str(A.__dict__); print A.foo; a=A(); print a.foo; a.foo=13; print a.foo; {'__dict__': <attribute '__dict__' of 'A' objects>,'foo': <__main__.simpleDescriptor object at 0x00C46930>,'__doc__': None} None None None class simpleDescriptor(object): def __init__(self): self.result=None; def __get__(self,type=None) : return self.result-10; def __set__(self,val): self.result=val+3; print self.result; def __del__(self,obj): pass class A(object): foo=simpleDescriptor(); a=A(); a.foo=13; print a.foo; 打印的输出结果为: 16 6 第一个16为我们在对a.foo赋值的时候,人为的将13加上3后作为foo的值,第二个6是我们在返回a.foo之前人为的将它减去了10。 class B(object): foo=1.3; b=B(); print b.__dict__ #print b.bar; b.bar=13; print b.__dict__ print b.bar; 输出结果为: {} {'bar': 13} 13 可见这里在实例b.__dict__里找到了bar属性,所以这次可以获取13了 def hello(): pass print dir(hello) ['__call__','__class__','__delattr__','__dict__','__doc__','__get__','__getattribute__','__hash__','__init__','__module__','__name__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__str__','func_closure','func_code','func_defaults','func_dict','func_doc','func_globals','func_name'] class simpleDescriptor(object): def __get__(self,type=None) : return 'get',self,type; class D(object): foo=simpleDescriptor(); d=D(); print d.foo; d.foo=15; print d.foo; 输出: ('get',<__main__.simpleDescriptor object at 0x00C46870>,<__main__.D object at 0x00C46890>,<class '__main__.D'>) 15 class D(object): def __getattr__(self,attr): return attr; #return self.attr; d=D(); print d.foo,type(d.foo); d.foo=15; print d.foo; 输出: foo <type 'str'> 15 可以看的出来Python在实在找不到方法的时候,就会求助于__getattr__方法。 class D(object): def __getattr__(self,attr): #return attr; return self.attr; d=D(); print d.foo,type(d.foo); d.foo=15; print d.foo; RuntimeError: maximum recursion depth exceeded (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |