Python 学习笔记 -- 装饰器
1 #修饰符的作用就是为已经存在的对象添加额外的功能 2 #实例: 3 import time 4 5 def timesLong(fun): 6 x = 0 7 def call(): 8 start = time.clock() 9 print("时钟开始!") 10 fun() 11 end = time.clock() 12 print("时钟结束!") 13 return "函数运行累积用时 %s 秒" % (end - start) 14 return call 15 16 @timesLong 17 def func(): 18 x = 0 19 for i in range(100): 20 x += i 21 22 print(x) 23 24 print(func()) 25 26 #分析结果: 27 #实际上print(func()) = print(timesLong(func)()) 28 #证明: 29 def func_test(): 30 x = 0 31 for i in range(100): 32 x += i 33 34 print(x) 35 36 print(timesLong(func_test)()) 37 #流程即:调用装饰器函数 --》 将佩戴装饰器的函数名传入其中 38 39 #------------------------------------------------------------------ 40 #property 装饰器版使用 41 42 43 class Code: 44 def __init__(self,size=10): 45 self.__size = size 46 47 @property 48 def size(self): 49 return self.__size 50 51 @size.setter 52 def size(self,value): 53 self.__size = value 54 55 @size.deleter 56 def size(self): 57 del self.__size 58 59 test = Code() 60 print(test.size) 61 test.size = 100 62 print(test.size) 63 del test.size 64 try: 65 print(test.size) 66 except: 67 print("test._Code__size 已被删除")