打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python中用MetaClass实现委托、不可变集合
     委托(delegate)是许多设计模式(如Decorator, Proxy)的基础,实现委托的一般方法是在委托类为每个需要委托的方法定义一个方法,它的仅有的实现就是对被委托对象调用同样的方法。例如,要实现ImmutableList,可以这样做:
Python代码  
  1. class ImmutableList(object):  
  2.     def __init__(self, delegate):  
  3.         self.delegate = delegate  
  4.   
  5.     def __getitem__(self, i):  
  6.         return self.delegate.__getitem__(i)  
  7.   
  8.     def __getslice__(self, i, j):  
  9.         return self.delegate.__getslice__(i, j)  
  10.   
  11.     def __len__(self):  
  12.         return self.delegate.__len(self)  
  13.   
  14.     def index(self, v):  
  15.         return self.delegate.index(v)  
  16.   
  17.     # ... more ...  

显然写这样的方法很是枯燥乏味,幸而在python中可以不需这样做,因为在python中类的方法可以动态添加, 说白其实就是给类添加属性,只是它的属性恰好是个函数罢了。给实例添加属性可以用__new__方法,而给类添加属性就要依赖metaclass了。好了,我们来看怎样用metaclass来实现委托。
Python代码  
  1. class DelegateMetaClass(type):  
  2.     def __new__(cls, name, bases, attrs):  
  3.         methods = attrs.pop('delegated_methods', ())   
  4.         for m in methods:  
  5.             def make_func(m):  
  6.                 def func(self, *args, **kwargs):  
  7.                     return getattr(self.delegate, m)(*args, **kwargs)  
  8.                 return func  
  9.   
  10.             attrs[m] = make_func(m)  
  11.         return super(DelegateMetaClass, cls).__new__(cls, name, bases, attrs)  
  12.   
  13. class Delegate(object):  
  14.     __metaclass__ = DelegateMetaClass  
  15.   
  16.     def __init__(self, delegate):  
  17.         self.delegate = delegate  

有了上面的,实现ImmutableList就很简单了,只需要继承Delegate,并定义需要委托的方法就好了:
Python代码  
  1. class ImmutableList(Delegate):  
  2.     delegated_methods = ( '__contains__', '__eq__', '__getitem__', '__getslice__',   
  3.                          '__str__', '__len__', 'index', 'count')  

再实现ImmutableDict:
Python代码  
  1. class ImmutableDict(Delegate):  
  2.     delegated_methods = ('__contains__', '__getitem__', '__eq__', '__len__', '__str__',   
  3.             'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'values')  

很简单吧!其实DelegateMetaClass还是很复杂的,尤其对于初学者理解起来很费劲,我可能下次会写点这方面的东西。顺便说下,django大量用到metaclass。 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
十九、Python MetaClass元类详解
改变python对象的黑魔法metaclass
[精]两句话掌握 Python 最难知识点:元类
Python的元编程能力
python 学习-打开潘多拉的魔盒-元类(metaclass)学习
Python面向对象特征总结
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服