1 import time 2 def timer(func): #timer(test1) func=test1 3 def deco(*args,**kwargs): 4 start_time=time.time() 5 res=func(*args,**kwargs) #run test1() 6 stop_time=time.time() 7 print("the func run time is %s" %(stop_time-start_time)) 8 return res 9 return deco 10 @timer #test1=timer(test1) 11 def test1(): 12 time.sleep(3) 13 print("in the test1") 14 15 # 向函數內傳遞參數須要在裝飾器內部使用非固定參數*args和**kwargs 16 @timer #test2=timer(test2) 17 def test2(name): 18 time.sleep(2) 19 print("test2:",name) 20 21 #獲取函數的返回值,須要將func的運行結果賦值給變量res 22 @timer 23 def test3(): 24 return "this is test3 name" 25 26 #調用 27 test1() 28 test2("ssss") 29 print(test3())
1 import time 2 def timmer(func): 3 def warpper(*args,**kwargs): 4 start_time=time.time() 5 func() 6 stop_time=time.time() 7 print("the func run time is %s" %(stop_time-start_time)) 8 return warpper 9 @timmer 10 def test1(): 11 time.sleep(3) 12 print("in the test1") 13 test1()
1 x=0 2 def grandpa(): 3 x=1 4 def dad(): 5 x=2 6 def son(): 7 x=3 8 print(x) 9 son() 10 dad() 11 grandpa()
1 def fib(max): 2 n,a,b=0,0,1 3 while n<max: 4 yield b #轉換成生成式 5 a,b=b,a+b 6 n+=1 7 return "--done--" 8 g=fib(100) 9 while True: 10 try: 11 n=g.__next__() #獲取下一個數值 12 print(n) 13 except StopIteration as e: #超出範圍處理 14 print("Generator return value:",e.value) 15 break
1 import time 2 def consumer(name): #消費者 3 print("%s 準備吃包子啦!"%name) 4 while True: 5 baozi=yield 6 print("包子[%s]來了,被[%s]吃了!"%(baozi,name)) 7 def producer(name): 8 c=consumer("A") 9 c2=consumer("B") 10 c.__next__() 11 c2.__next__() 12 print("老子開始準備作包子了") 13 for i in range(10): 14 time.sleep(1) 15 print("作了兩個包子") 16 c.send(i) 17 c2.send(i) 18 #協程 19 producer("alex") 20 21 # c=consumer("ChenRonghua") 22 # c.__next__() 23 # b1="韭菜餡" 24 # c.send(b1) #send給yield傳值 25 # #next只喚醒生成器可是不傳值,send喚醒後傳值
import json info={ "name":"alex", "age":22 } f=open("test.txt","w") f.write(json.dumps(info)) f.close()
import json f=open("test.txt","r") data=json.loads(f.read()) print(data["age"])
import pickle info={ "name":"alex", "age":22 } f=open("test.txt","wb") f.write(pickle.dumps(info)) #或者pickle.dump(info,f) f.close()
import pickle f=open("test.txt","rb") data=pickle.loads(f.read()) #或者data=pickle.load(f) print(data["age"])