Python的descriptor (2)
前面说了descriptor,这个东西其实和Java的setter,getter有点像。但这个descriptor和上文中我们开始提到的函数方法这些东西有什么关系呢?
所有的函数都可以是descriptor,因为它有__get__方法。
- >>> def hello():
- pass
- >>> dir(hello)
- ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '<span style="color: #ff0000;">__get__</span>
- ', '__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']
- >>>
注意,函数对象没有__set__和__del__方法,所以它是个non-data descriptor.
方法其实也是函数,如下:
- >>> class T(object):
- def hello(self):
- pass
- >>> T.__dict__['hello']
- <function hello at 0x00CD7EB0>
- >>>
或者,我们可以把方法看成特殊的函数,只是它们存在于类 中,获取函数属性时,返回的不是函数本身(比如上面的<function hello at 0x00CD7EB0>),而是返回函数的__get__方法的返回值,接着上面类T的定义:
>>> T.hello 获取T的hello属性,根据查找策略,从T的__dict__中找到了,找到的是<function hello at 0x00CD7EB0>,但不会直接返回<function hello at 0x00CD7EB0>,因为它有__get__方法,所以返回的是调用它的__get__(None, T)的结果:一个unbound方法。 <unbound method T.hello>
>>> f = T.__dict__['hello'] #直接从T的__dict__中获取hello,不会执行查找策略,直接返回了<function hello at 0x00CD7EB0> >>> f
<function hello at 0x00CD7EB0>
>>> t = T()
>>> t.hello #从实例获取属性,返回的是调用<function hello at 0x00CD7EB0>的__get__(t, T)的结果:一个bound方法。 <bound method T.hello of <__main__.T object at 0x00CDAD10>>
>>>
为了证实我们上面的说法,在继续下面的代码(f还是上面的<function hello at 0x00CD7EB0>):
- >>> f.__get__(None, T)
- <unbound method T.hello>
- >>> f.__get__(t, T)
- <bound method T.hello of <__main__.T object at 0x00CDAD10>>
好极了!
总结一下:
1.所有的函数都有__get__方法
2.当函数位于类的__dict__中时,这个函数可以认为是个方法,通过类或实例获取该函数时,返回的不是函数本身,而是它的__get__方法返回值。
我承认我可能误导你认为方法就是函数,是特殊的函数。其实方法和函数还是有区别的,准确的说:方法就是方法,函数就是函数。
- >>> type(f)
- <type 'function'>
- >>> type(t.hello)
- <type 'instancemethod'>
- >>> type(T.hello)
- <type 'instancemethod'>
- >>>
函数是function类型的,method是instancemethod(这是普通的实例方法,后面会提到classmethod和staticmethod)。
关于unbound method和bound method,再多说两句。在c实现中,它们是同一个对象(它们都是instancemethod类型的),我们先看看它们里面到底是什么
- >>> dir(t.hello)
- ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__',
- '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
- '__str__', 'im_class', 'im_func', 'im_self']
__call__说明它们是个可调用对象,而且我们还可以猜测,这个__call__的实现应该大致是:转调另外一个函数(我们期望的哪个,比如上面的hello),并以对象作为第一参数。
要 注意的是im_class,im_func,im_self。这几个东西我们并不陌生,在t.hello里,它们分别代表T,hello(这里是存储在 T.__dict__里的函数hello)和t。有了这些我们可以大致想象如何纯Python实现一个instancemethod了:)。
其实还有几个内建函数都和descriptor有关,下面简单说说。
classmethod
classmethod能将一个函数转换成类方法,类方法的第一个隐含参数是类本身 (普通方法的第一个隐含参数是实例本身),类方法即可从类调用,也可以从实例调用(普通方法只能从实例调用)。
- >>> class T(object):
- def hello(cls):
- print 'hello', cls
- hello = classmethod(hello) #两个作用:把hello装换成类方法,同时隐藏作为普通方法的hello
- >>> t = T()
- >>> t.hello()
- hello <class '__main__.T'>
- >>> T.hello()
- hello <class '__main__.T'>
- >>>
注意:classmethod是个类,不是函数。classmethod类有__get__方法,所以,上面的t.hello和T.hello获得实际上是classmethod的__get__方法返回值
- >>> t.hello
- <bound method type.hello of <class '__main__.T'>>
- >>> type(t.hello)
- <type 'instancemethod'>
- >>> T.hello
- <bound method type.hello of <class '__main__.T'>>
- >>> type(T.hello)
- <type 'instancemethod'>
- >>>
从 上面可以看出,t.hello和T.hello是instancemethod类型的,而且是绑定在T上的。也就是说classmethod的 __get__方法返回了一个instancemethod对象。从前面对instancemethod的分析上,我们应该可以推断:t.hello的 im_self是T,im_class是type(T是type的实例),im_func是函数hello
- >>> t.hello.im_self
- <class '__main__.T'>
- >>> t.hello.im_class
- <type 'type'>
- >>> t.hello.im_func
- <function hello at 0x011A40B0>
- >>>
完全一致!所以实现一个纯Python的classmethod也不难:)
staticmethod
staticmethod能将一个函数转换成静态方法,静态方法没有隐含的第一个参数。
- class T(object):
- def hello():
- print 'hello'
- hello = staticmethod(hello)
- >>> T.hello() #没有隐含的第一个参数
- hello
- >>> T.hello
- <function hello at 0x011A4270>
- >>>
T.hello直接返回了一个函数。猜想staticmethod类的__get__方法应该是直接返回了对象本身。
还有一个property,和上面两个差不多,它是个data descriptor。
Python的descriptor (2)的更多相关文章
- python's descriptor II
[python's descriptor II] For instance, a.x has a lookup chain starting with a.__dict__['x'], then ty ...
- python's descriptor
[python's descriptor] 1.实现了以下三个方法任意一个的,且作为成员变量存在的对象,就是descriptor. 1)object.__get__(self, instance, o ...
- python中descriptor的应用
[python中descriptor的应用] 1.classmethod. 1)classmethod的应用. 2)classmethod原理. 2.staticmethod. 1)staticmet ...
- Python的Descriptor和Property混用
一句话,把Property和Descriptor作用在同一个名字上,就只有Property好使.
- python中的 descriptor
学好和用好python, descriptor是必须跨越过去的一个点,现在虽然Python书籍花样百出,但是似乎都是在介绍一些Python库而已,对Python语言本身的关注很少,或者即使关注了,但是 ...
- Python描写叙述符(descriptor)解密
Python中包括了很多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...
- Python——描述符(descriptor)解密
本文由 极客范 - 慕容老匹夫 翻译自 Chris Beaumont.欢迎加入极客翻译小组,同我们一道翻译与分享.转载请参见文章末尾处的要求. Python中包含了许多内建的语言特性,它们使得代码简洁 ...
- 【python】类(资料+疑惑)
1.http://python-china.org/t/77 有关method binding的理解 2.[Python] dir() 与 __dict__,__slots__ 的区别 3.Descr ...
- python高级编程之最佳实践,描述符与属性01
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #最佳实践 """ 为了避免前面所有的 ...
随机推荐
- 《c程序设计语言》读书笔记--统计总的字符数,打印能打印的最多字符
#include <stdio.h> #define MAXLINE 10 int getline(char line[],int maxline); void copy(char to[ ...
- WINCE设备开机灰屏问题(很怪异)
WINCE设备开机灰屏问题(很怪异) 1. 问题现象 图1 无法进入系统,虽然没有调试信息,但应该可以判断是程序跑飞了.我们这款产品用到3种显示屏(采用不同的驱动IC),可是测试发现1和2号屏 ...
- 如何实现wpf的多国语言
http://www.cnblogs.com/horan/archive/2012/04/20/wpf-multilanguage.html 4.0版本的locbaml http://michaels ...
- 【分享】哪个OS X版本支持哪个Xcode的版本?
在安装Xcode时,会碰到跟OS X操作系统匹配的问题,对照下下面几个表,以免给自己带来编译不过或者奇怪的错误等问题 以下列表来自网络: Xcode 1.0 - Xcode 2.x (before i ...
- 【转】Windows Server 2008 以上服务器配置SMTP
建立 SMTP 伺服器 [除非特別說明,否則本主題中的內容適用於 BizTalk Server 2013 和 2013 R2.]原文链接:https://msdn.microsoft.com/zh-t ...
- [转]使用 jQuery Mobile 与 HTML5 开发 Web App —— jQuery Mobile 事件详解
在前文<使用 jQuery Mobile 与 HTML5 开发 Web App —— jQuery Mobile 默认配置与事件基础>中,Kayo 对 jQuery Mobile 事件的基 ...
- toB的产品经理和toc产品经理区别
腾讯产品经理现身说法 曾经在UC做过2年to c的app,现在在腾讯做to b的产品. 做to c产品的时候,我很瞧不起做to b产品的同学,认为他们不过是做支撑的. 后来,我参与了一个to b平台级 ...
- (二)深入梯度下降(Gradient Descent)算法
一直以来都以为自己对一些算法已经理解了,直到最近才发现,梯度下降都理解的不好. 1 问题的引出 对于上篇中讲到的线性回归,先化一个为一个特征θ1,θ0为偏置项,最后列出的误差函数如下图所示: 手动求解 ...
- QR二维码(转)
二维码又称QR Code,QR全称Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的Bar Code条形码能存更多的信息,也能表示更多的数据类型:比如:字符,数字, ...
- RAC 数据库的启动与关闭
RAC数据库与单实例的差异主要表现在多个实例通过集群件来统一管理共享的资源.因此原有的单实例的管理方式,如数据库.监听器等的关闭启动等可以使用原有的方式进行,也可以通过集群管理工具,命令行来集中管理, ...