标签:block elf exist 使用 instance ini isp ica call
The implementation works through a precedence chain that gives data descriptors priority over instance variables, instance variables priority over non-data descriptors, and assigns lowest priority to__getattr__()
if provided.
1 #coding=utf-8 2 class DataDescriptor(object): 3 def __init__(self, init_value): 4 self.value = init_value 5 6 def __get__(self, instance, typ): 7 return ‘DataDescriptor __get__‘ 8 9 def __set__(self, instance, value): 10 print (‘DataDescriptor __set__‘) 11 self.value = value 12 13 class NonDataDescriptor(object): 14 def __init__(self, init_value): 15 self.value = init_value 16 17 def __get__(self, instance, typ): 18 return(‘NonDataDescriptor __get__‘) 19 20 class Base(object): 21 dd_base = DataDescriptor(0) 22 ndd_base = NonDataDescriptor(0) 23 24 25 class Derive(Base): 26 dd_derive = DataDescriptor(0) 27 ndd_derive = NonDataDescriptor(0) 28 same_name_attr = ‘attr in class‘ 29 30 def __init__(self): 31 self.not_des_attr = ‘I am not descriptor attr‘ 32 self.same_name_attr = ‘attr in object‘ 33 34 def __getattr__(self, key): 35 return ‘__getattr__ with key %s‘ % key 36 37 def change_attr(self): 38 self.__dict__[‘dd_base‘] = ‘dd_base now in object dict ‘ 39 self.__dict__[‘ndd_derive‘] = ‘ndd_derive now in object dict ‘ 40 41 def main(): 42 b = Base() 43 d = Derive() 44 print ‘Derive object dict‘, d.__dict__ 45 assert d.dd_base == "DataDescriptor __get__" 46 assert d.ndd_derive == ‘NonDataDescriptor __get__‘ 47 assert d.not_des_attr == ‘I am not descriptor attr‘ 48 assert d.no_exists_key == ‘__getattr__ with key no_exists_key‘ 49 assert d.same_name_attr == ‘attr in object‘ 50 d.change_attr() 51 print ‘Derive object dict‘, d.__dict__ 52 assert d.dd_base != ‘dd_base now in object dict ‘ 53 assert d.ndd_derive == ‘ndd_derive now in object dict ‘ 54 55 try: 56 b.no_exists_key 57 except Exception, e: 58 assert isinstance(e, AttributeError) 59 60 if __name__ == ‘__main__‘: 61 main()
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
标签:block elf exist 使用 instance ini isp ica call
原文地址:http://www.cnblogs.com/xybaby/p/6270551.html