1 # -*- coding: utf-8 -*- 2 class Des(object): 3 def __init__(self, init_value): 4 self.value = init_value 5 6 def __get__(self, instance, typ): 7 print(‘call __get__‘, instance, typ) 8 return self.value 9 10 def __set__(self, instance, value): 11 print (‘call __set__‘, instance, value) 12 self.value = value 13 14 def __delete__(self, instance): 15 print (‘call __delete__‘, instance) 16 17 class Widget(object): 18 t = Des(1) 19 20 def main(): 21 w = Widget() 22 print type(w.t) 23 w.t = 1 24 print w.t, Widget.t 25 del w.t 26 print w.t 27 28 29 if __name__==‘__main__‘: 30 main()
object.
__get__
(self, instance, owner):return valueobject.
__set__
(self, instance, value):return Noneobject.
__delete__
(self, instance): return None__slots__ are implemented at the class level by creating descriptors for each variable name
1 class TestProperty(object): 2 def __init__(self): 3 self.__a = 1 4 5 @property 6 def a(self): 7 return self.__a 8 9 @a.setter 10 def a(self, v): 11 print(‘output call stack here‘) 12 self.__a = v 13 14 if __name__==‘__main__‘: 15 t = TestProperty() 16 print t.a 17 t.a = 2 18 print t.a
1 import functools, time 2 class cached_property(object): 3 """ A property that is only computed once per instance and then replaces 4 itself with an ordinary attribute. Deleting the attribute resets the 5 property. """ 6 7 def __init__(self, func): 8 functools.update_wrapper(self, func) 9 self.func = func 10 11 def __get__(self, obj, cls): 12 if obj is None: return self 13 value = obj.__dict__[self.func.__name__] = self.func(obj) 14 return value 15 16 class TestClz(object): 17 @cached_property 18 def complex_calc(self): 19 print ‘very complex_calc‘ 20 return sum(range(100)) 21 22 if __name__==‘__main__‘: 23 t = TestClz() 24 print ‘>>> first call‘ 25 print t.complex_calc 26 print ‘>>> second call‘ 27 print t.complex_calc
原文:http://www.cnblogs.com/xybaby/p/6266686.html