class ImmutableList(object): def __init__(self, delegate): self.delegate = delegate def __getitem__(self, i): return self.delegate.__getitem__(i) def __getslice__(self, i, j): return self.delegate.__getslice__(i, j) def __len__(self): return self.delegate.__len(self) def index(self, v): return self.delegate.index(v) # ... more ...
显然写这样的方法很是枯燥乏味,幸而在python中可以不需这样做,因为在python中类的方法可以动态添加, 说白其实就是给类添加属性,只是它的属性恰好是个函数罢了。给实例添加属性可以用__new__方法,而给类添加属性就要依赖metaclass了。好了,我们来看怎样用metaclass来实现委托。
class DelegateMetaClass(type): def __new__(cls, name, bases, attrs): methods = attrs.pop('delegated_methods', ()) for m in methods: def make_func(m): def func(self, *args, **kwargs): return getattr(self.delegate, m)(*args, **kwargs) return func attrs[m] = make_func(m) return super(DelegateMetaClass, cls).__new__(cls, name, bases, attrs) class Delegate(object): __metaclass__ = DelegateMetaClass def __init__(self, delegate): self.delegate = delegate
有了上面的,实现ImmutableList就很简单了,只需要继承Delegate,并定义需要委托的方法就好了:
class ImmutableList(Delegate): delegated_methods = ( '__contains__', '__eq__', '__getitem__', '__getslice__', '__str__', '__len__', 'index', 'count')
再实现ImmutableDict:
class ImmutableDict(Delegate): delegated_methods = ('__contains__', '__getitem__', '__eq__', '__len__', '__str__', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'values')
很简单吧!其实DelegateMetaClass还是很复杂的,尤其对于初学者理解起来很费劲,我可能下次会写点这方面的东西。顺便说下,django大量用到metaclass。