2012年09月06日 星期四 19:09
class DictProperty(object): ''' Property that maps to a key in a local dict-like attribute. ''' def __init__(self, attr, key=None, read_only=False): self.attr, self.key, self.read_only = attr, key, read_only def __call__(self, func): functools.update_wrapper(self, func, updated=[]) self.getter, self.key = func, self.key or func.__name__ return self def __get__(self, obj, cls): if obj is None: return self key, storage = self.key, getattr(obj, self.attr) if key not in storage: storage[key] = self.getter(obj) return storage[key] def __set__(self, obj, value): if self.read_only: raise AttributeError("Read-Only property.") getattr(obj, self.attr)[self.key] = value def __delete__(self, obj): if self.read_only: raise AttributeError("Read-Only property.") del getattr(obj, self.attr)[self.key]
若是用上面的类去装饰一个方法,例如:
@DictProperty('environ', 'bottle.request.cookies', read_only=True)
def test(self):print "in test"
那么当使用a = self.test时,是使用的__get__函数,还是test本身?
2012年09月26日 星期三 21:38
__get__ 是指使用map[key]形式取值的实现吧
Zeuux © 2024
京ICP备05028076号