---
title: "【转】探索Python下的property, classmethod, staticmethod的实现"
author: "ooaer"
date: "2013-04-08T21:22:05Z"
tags: []
categories: ["编程语言"]
slug: "python-property-classmethod-staticmethod"
draft: false
lastmod: "2013-04-08T21:22:05Z"
id: 1844106
url: "https://ooaer.iteye.com/blog/1844106"
---

转：http://marlonyao.iteye.com/blog/679425 Python有几个内置方法poperty, classmethod, staticmethod，其中property用来将方法变成属性，而classmethod将一个类的函数变成类方法，staticmethod将类的一个函数变成静态方法。它们是如何使用的，我这里就不讲了，只讲它们可能是怎样实现的。之所以说“可能”，是因为我并不确定，我对Python也只是初学，并且这里讲的可能也只是其中一种实现方式而已。 在讲实现之前我需要稍微介绍一下Python中的Descriptor，Descriptor提供了一种强大的机制来实现对属性的自定义访问。我建议大家都看下Shalabh Chaturvedi的这篇文章，我这篇博客不过是补充它只是简单提到的东西而已，甚至例子也大部分来源于那篇文章。 下面是一个Descriptor的例子（该例子来源于Shalabh Chaturvedi的文章）： Python代码 class Desc(object): def \_\_get\_\_(self, obj, cls=None): print '\_\_get\_\_: %s' % ((self, obj, cls),) def \_\_set\_\_(self, obj, val): print '\_\_set\_\_: %s' % ((self, obj, val),) def \_\_delete\_\_(self, obj): print '\_\_delete\_\_: %s' % ((self, obj), ) class C(object): d = Desc() cobj = C() x = cobj.d cobj.d = 'setting a value' cobj.\_\_dict\_\_\['d'] = 'try to force a value' x = cobj.d del cobj.d x = C.d C.d = 'setting a value on class' 上面的代码输出： Python代码 \_\_get\_\_: (&lt;\_\_main\_\_.Desc object at 0xb74b33cc&gt;, &lt;\_\_main\_\_.C object at 0xb74b342c&gt;, ) \_\_set\_\_: (&lt;\_\_main\_\_.Desc object at 0xb74b33cc&gt;, &lt;\_\_main\_\_.C object at 0xb74b342c&gt;, 'setting a value') \_\_get\_\_: (&lt;\_\_main\_\_.Desc object at 0xb74b33cc&gt;, &lt;\_\_main\_\_.C object at 0xb74b342c&gt;, ) \_\_delete\_\_: (&lt;\_\_main\_\_.Desc object at 0xb74b33cc&gt;, &lt;\_\_main\_\_.C object at 0xb74b342c&gt;) \_\_get\_\_: (&lt;\_\_main\_\_.Desc object at 0xb74b33cc&gt;, None, ) 我不想作太多解释，只需要注意访问和给cobj.d赋值调用的是Desc的\_\_get\_\_和\_\_set\_\_方法，即使通过\_\_dict\_\_来覆盖cobj的d属性时也是如此。（需要注意的是：Descriptor分为Data Descriptor和Non-Data Descriptor，区别在于Data Descriptor同时实现\_\_get\_\_和\_\_set\_\_方法，而Non-Data只实现了\_\_get\_\_方法，两者的行为不同，上面的例子是Data Descriptor）。 接下来，我们来看如何利用Descriptor来实现Python内置classmethod方法所提供的功能。为了和内置classmethod区别，我将它命名为myclassmethod，它的实现如下： Python代码 def myclassmethod(clsmethod): return ClassMethodDesc(clsmethod) class ClassMethodDesc(object): def \_\_init\_\_(self, clsmethod): self.clsmethod = clsmethod def \_\_get\_\_(self, obj, cls=None): def wrap(\*args, \*\*kwargs): return self.clsmethod(cls, \*args, \*\*kwargs) return wrap myclassmethod返回ClassMethodDesc，它是一个Non-Data Descriptor，只实现了\_\_get\_\_方法，它会返回一个函数，调用这个函数时，它会将调用委托给clsmethod，但第一个参数设置成会传递一个cls参数。它的使用方式和内置的classmethod实现一样，下面是个例子： Python代码 class ClassMethodDemo(object): def cls\_method(cls): print 'You called class %s' % cls cls\_method = myclassmethod(cls\_method) if \_\_name\__ == '\_\_main\_\_': obj = ClassMethodDemo() obj.cls\_method() ClassMethodDemo.cls\_method() 上面代码输出： Python代码 You called class You called class 实现static方法同样很简单，这里就不写了。下面的myproperty方法实现和内置property基本一样的功能，只是它的参数都是必需的，并且只接受getmethod和setmethod两个方法，不再作解释. Python代码 def myproperty(getmethod, setmethod): return PropertyMethodDesc(getmethod, setmethod) class PropertyMethodDesc(object): def \_\_init\_\_(self, getmethod, setmethod): self.getmethod = getmethod self.setmethod = setmethod def \_\_get\_\_(self, obj, cls=None): return self.getmethod(obj) def \_\_set\_\_(self, obj, val): return self.setmethod(obj, val) class PropertyDemo(object): def get\_a(self): print 'get\_a invoked' return self.\_\_dict\_\_\['a'] def set\_a(self, val): print 'set\_a as %s' % val self.\_\_dict\_\_\['a'] = val a = myproperty(get\_a, set\_a) if \_\_name\__ == '\_\_main\_\_': obj = PropertyDemo() obj.a = 5 print obj.a