在讲实现之前我需要稍微介绍一下Python中的Descriptor,Descriptor提供了一种强大的机制来实现对属性的自定义访问。我建议大家都看下Shalabh Chaturvedi的 这篇文章,我这篇博客不过是补充它只是简单提到的东西而已,甚至例子也大部分来源于那篇文章。
下面是一个Descriptor的例子(该例子来源于Shalabh Chaturvedi的文章):
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'
上面的代码输出:
__get__: (<__main__.Desc object at 0xb74b33cc>, <__main__.C object at 0xb74b342c>,) __set__: (<__main__.Desc object at 0xb74b33cc>, <__main__.C object at 0xb74b342c>, 'setting a value') __get__: (<__main__.Desc object at 0xb74b33cc>, <__main__.C object at 0xb74b342c>, ) __delete__: (<__main__.Desc object at 0xb74b33cc>, <__main__.C object at 0xb74b342c>) __get__: (<__main__.Desc object at 0xb74b33cc>, 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,它的实现如下:
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实现一样,下面是个例子:
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()
上面代码输出:
You called classYou called class
实现static方法同样很简单,这里就不写了。下面的myproperty方法实现和内置property基本一样的功能,只是它的参数都是必需的,并且只接受getmethod和setmethod两个方法,不再作解释.
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