1. 程式人生 > >python學習之路第四周彙總

python學習之路第四周彙總

  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 # Author:Source
  4 import time,functools
  5 #裝飾器。本質上是函式,作用是為其它函式新增附加功能。
  6 #原則:1、不能修改被裝飾的函式的原始碼 2、不能修改被裝飾的函式的呼叫方式。
  7 #為什麼說本質上是函式呢?
  8 def test():#關鍵字是def
  9     '別害怕,僅僅只是一個測試函式而已'
 10     print("Don't worry.Just test.")
 11 func = test#func變量表示的是一個函式物件的例項
12 print(func)#不帶括號表示一個函式 13 print(func())#帶括號時候直接呼叫函式 14 def statistics_time(fuc): 15 '統計程式運算時間的函式' 16 time_begin = time.time() 17 fuc() 18 time_finish = time.time() 19 print("The function spend %s to run."%(time_finish-time_begin)) 20 statistics_time(test)#它違反了裝飾器的第二個原則
21 def statistics_time_2(fuc): 22 print(fuc) 23 return test 24 test = statistics_time_2('ojbk') 25 test()#其中的print(fuc)作為了增加的功能 26 #高階函式 27 #其一,在不修改函式的呼叫方式的情況下,返回值中包含函式名。其二,在不修改裝飾函式的原始碼的情況下,把一個函式名當作實參傳給另一個函式 28 #滿足其中一個就是高階函式 29 def timer():#函式巢狀 30 def deco(): 31 pass 32
#高階函式 + 函式巢狀 =》裝飾器 33 def function_run_time(func): 34 '統計程式執行時間的高階函式' 35 def internal(): 36 time_begin = time.time() 37 func() 38 time_finish = time.time() 39 print("The function spend %s to run."%(time_finish- time_begin)) 40 return internal 41 @function_run_time #類似與 test_1 = funtion_run_time(test_1) 42 def test_1(): 43 '只是一個測試小程式而已' 44 time.sleep(1) 45 print("Just test again.") 46 #test_1() 47 #匿名函式lambda 48 x_1 = lambda x:x+7 49 print(x_1(7)) 50 (lambda n:print(n))(5) 51 x_2 = lambda n:print(n) 52 x_2(5) 53 #三元運算 54 x_3 = lambda x:1 if x<5 else 2 55 print(x_3(1),x_3(5)) 56 #filter()按照一定的規則過濾+三元運算 57 res = filter(lambda n:n>5,range(10)) 58 for i in res: 59 print(i) 60 #map(),對傳入的值按規律處理並覆蓋原有資料。 61 x_4 = map(lambda x:x*2,range(10)) 62 for i in x_4: 63 print(i) 64 x_5 = [i*2 for i in range(10)]#列表生成式 65 print(x_5) 66 x_6= [lambda i:i*2 for i in range(10)]#不曉得為什麼讀出來的是地址 67 #reduce,需要先呼叫fuctools。函式將一個數據集合中的所有資料進行下列操作:用傳給reduce中的函式function(有兩個引數)先對集合 68 #中的第1、2個元素進行操作,得到的結果再與第三個資料用function函式運算,最後得到一個結果。 69 def multiplication(x,y): 70 return x*y 71 print(functools.reduce(multiplication,[1,2,3,4,5])) 72 print(functools.reduce(lambda x,y:x*y,[1,2,3,4,5])) 73 print(functools.reduce(lambda x,y:x+y,[1,2,3,4,5])) 74 #生成器,都是迭代器物件只有在呼叫的時候才會生成相應的資料 75 #for example 76 builder = (i*2 for i in range(3)) 77 # print(builder)#顯示的是所在記憶體地址 78 # print(builder.__next__()) 79 # print(builder.__next__()) 80 # print(builder.__next__())#只記住當前位置,超出會報錯 81 # print(next(builder)) 82 # print(next(builder)) 83 # print(next(builder)) 84 # for i in builder:#要用這種方式才可以呼叫 85 # print(i) 86 #斐波那契函式,第三個數等於前兩個數的和。 87 '''def Fibonacci(time): 88 x,y =0,1, 89 while time>0: 90 #print(y) 91 yield y#yield 的作用就是把一個函式變成一個 generator 92 x,y = y,x+y#帶有 yield 的函式不再是一個普通函式,Python直譯器會將其視為一個 generator 93 time -=1#執行到 yield b 時,fab 函式就返回一個迭代值,下次迭代時,程式碼從 yield b 的下一條語句繼續執行, 94 # 而函式的本地變數看起來和上次中斷執行前是完全一樣的,於是函式繼續執行,直到再次遇到 yield 95 return '-----done-----' 96 g = Fibonacci(10) 97 while True: 98 try:#正常執行程式執行try下的程式,執行出錯時執行except裡的 99 x = next(g) 100 print("g:",x) 101 except StopIteration as e: 102 print("Generator return value:",e.value) 103 break''' 104 '''def producer(name): 105 c1 = consumer("A") 106 c2 = consumer("B") 107 c1.__next__() 108 c2.__next__() 109 print("開始準備做包子了!") 110 for i in range(10): 111 time.sleep(0) 112 print("做了兩個包子。") 113 c1.send(i) 114 c2.send(i) 115 def consumer(name): 116 print("準備吃包子了.") 117 while True: 118 baozi = yield 119 print("包子[%s]來了,被[%s]吃了!"%(baozi,name)) 120 producer('Souce')''' 121 #包子程式開始從producer執行,執行到__next__()時候,喚醒yield執行含有yield的conseumer。執行到yield的時候,儲存當前狀態,返回 122 #繼續執行producer,執行到producer的send後喚醒yield並傳值給yield然後繼續執行consumer。再次consumer的yield則儲存狀態返回到producer 123 #send繼續執行 124 #迭代器,可以直接作用於for迴圈的資料型別。 125 #可迭代物件(iterable)for example: 126 from collections import Iterable 127 print(isinstance([],Iterable))#列表 128 print(isinstance([i*2 for i in range(10)],Iterable))#列表生成式 129 print(isinstance(builder,Iterable))#生成器 130 print(isinstance((),Iterable))#元組 131 print(isinstance(set([1,1,2,3]),Iterable))#集合 132 print(isinstance({},Iterable))#列表 133 print(isinstance('',Iterable))#字串 134 #可以被next()函式呼叫並不斷返回下一個值的物件稱為迭代器:Iterator 135 #for example: 136 from collections import Iterator 137 print(isinstance(builder,Iterator))#生成器 138 print(isinstance([],Iterator)) 139 print(isinstance(iter({}),Iterator))#iter()可以把list、dict、str等Iterable變成Iterator 140 print(isinstance('',Iterator)) 141 #為什麼list、dict、str等資料型別不是Iterator 142 '''這是因為Python的Iterator物件表示的是一個數據流,Iterator物件可以被next()函式呼叫並不斷返回下一個資料,直到沒有資料 143 時丟擲StopIteration錯誤,可以把這個資料流看做是一個有序序列,但我們卻不能提前知道序列的長度,只能不斷通過next()函式實 144 現按需計算下一個資料,所以Iterator的計算是惰性的,只有在需要返回時它才會計算。 145 Iterator甚至可以表示一個無限大的資料流,例如全體自然數,而使用list是永遠不可能儲存全體自然數的。 146 ''' 147 #for迴圈的本質上是通過不斷呼叫next()函式實現的,例如: 148 #先獲得Iterator物件 149 it_tor = iter([1,2,3,4,5]) 150 while True: 151 try: 152 #獲得下一個值 153 x = next(it_tor) 154 print(x) 155 except StopIteration: 156 break 157 #裝飾器終極版,網站頁面的瀏覽許可權限制,也就是登入驗證。 158 '''user,pawd='source','123456' 159 def verification(way): 160 def select(func): 161 def verify(*args,**kwargs): 162 username = input('username:'.strip()) 163 password = input('password:'.strip()) 164 if way=='local': 165 if username == user and password == pawd: 166 print('\033[32;1mwelecome your enter!\033[0m'.capitalize()) 167 res = func(*args,**kwargs) 168 print('what?'.center(50,'*')) 169 return res 170 else: 171 print('\033[31;1minvalid username or password.\033[0m'.capitalize()) 172 elif way=='ldap': 173 print("\033[33;1mI haven't learned.\033[0m") 174 return verify 175 return select 176 def first_door(): 177 print('welcome to the first door.'.capitalize()) 178 @verification(way='local') #send_door = verify 179 def second_door(): 180 print('welcome to the second door.'.capitalize()) 181 return 'This Ok' 182 @verification(way='ldap') 183 def third_door(): 184 print('welcome to the third door.'.capitalize()) 185 first_door() 186 print(second_door()) 187 third_door()''' 188 #abs(),返回數字的絕對值 189 print(abs(-8)) 190 #all(),如果迭代器中所有元素都為真則返回真。記住一點非零為真。用於判斷給定的可迭代引數 iterable 中的所有元素是否都為 TRUE, 191 # 如果是返回 True,否則返回 False。 192 #元素除了是 0、空、FALSE 外都算 TRUE。 193 print(all((-8,2,3))) 194 iterable_list = [i*2 for i in range(10)] 195 print(all(iterable_list)) 196 #all()實質上是: 197 def all_function(iterable): 198 for element in iterable: 199 if not element: 200 return False 201 return True 202 print(all_function([-2,6,0])) 203 #any(),可迭代資料裡任意一個數據為真則返回真,空列表返回假。 204 print(any([0])) 205 print(any([0,1])) 206 #ascii(),把一個記憶體物件變為可列印字串的形式 207 print("just test.") 208 print(ascii("just test.")) 209 #bin(),將十進位制轉二進位制 210 for i in range(15): 211 print(bin(i)) 212 #bytearray(),能對資料進行修改。注意:字串不能修改,二進位制位元組格式不能修改。bytearray() 方法返回一個新位元組陣列。這個陣列 213 # 裡的元素是可變的,並且每個元素的值範圍: 0 <= x < 256。 214 #class bytearray([source[, encoding[, errors]]]) 215 print(bytearray([])) 216 a = bytearray([3,2,1])#如果 source 為整數,則返回一個長度為 source 的初始化陣列 217 print(a) 218 a.append(4) 219 a[0] = 5#修改字元 220 print(a) 221 bytearray_test = 'just test.' 222 b = bytearray(bytearray_test,'utf-8')#如果 source 為字串,則按照指定的 encoding 將字串轉換為位元組序列 223 print(b[0],b[1],b[2])#打印出來的是ASCII碼 224 b[0] = 97#能修改字元 225 print(b) 226 print(bytearray(iterable_list))#如果 source 為可迭代型別,則元素必須為[0 ,255] 中的整數 227 iterable_list[1]=4#修改 228 print(bytearray(iterable_list)) 229 #callable(),可不可以呼叫。注意:後面可以加括號的就是可以呼叫的。 230 print(callable(input)) 231 print(callable(type)) 232 #chr(),檢視數字對應的ascall。 233 print(chr(97)) 234 #ord(),檢視ascall對應的數字。 235 print(ord('d')) 236 #classmethod()修飾符對應的函式不需要例項。 237 # 化,不需要 self 引數,但第一個引數需要是表示自身類的 cls 引數,可以來呼叫類的屬性, 238 # 類的方法,例項化物件等。 239 class A(object): 240 bar = 1 241 def func1(self): 242 print("foo") 243 @classmethod 244 def func2(cls): 245 print("func2") 246 print(cls.bar) 247 cls().func1() 248 A.func2() 249 #compile,底層的用於將程式碼編譯的過程.將一個字串編譯為位元組程式碼。 250 str = "for i in range(10):print(i)" 251 c = compile(str,'',mode = 'exec') 252 exec(c) 253 #delattr()函式用於刪除屬性。delattr(x, 'foobar') 相等於 del x.foobar。 254 class coordinate: 255 x = 10 256 y = 8 257 z = 6 258 point = coordinate() 259 print("x = ",point.x) 260 print("y = ",point.y) 261 print("z = ",point.z) 262 delattr(coordinate,'x') 263 print("del x ") 264 print("y = ",point.y) 265 print("z = ",point.z) 266 #dict(),用於建立一個字典。 267 dic = dict()#建立一個空字典 268 print(dic) 269 dict1 = dict(a = 1 ,b ='b',c = 'good')#傳入關鍵字 270 print(dict1) 271 dict2 = dict(zip(['one','two','three'],[1,2,3]))#對映函式的方式構造字典 272 dict3 = dict([('nine',9),("eight",8),('seven',7)])#可迭代物件方式構造字典 273 print(dict2,dict3) 274 #dir(),檢視有什麼方法可以用。dir() 函式不帶引數時,返回當前範圍內的變數、方法和定義的型別列表;帶引數時,返回引數的屬性、 275 # 方法列表。如果引數包含方法__dir__(),該方法將被呼叫。如果引數不包含__dir__(),該方法將最大限度地收集引數資訊。 276 print(dir())#返回當前範圍內的變數、方法和定義的型別列表。 277 print(dir(dict))#帶引數時,返回引數的屬性、方法列表。 278 #divmod(a,b),相除返回商,餘數。 279 print(divmod(6,3)) 280 #eval(),將字串變成字典。注意(字元型別、加減乘除、難的不行).用來執行一個字串表示式,並返回表示式的值。 281 x = 3 282 print(eval('3*x')) 283 print(eval('pow(2,3)'))#2**3 284 print(eval('abs(-3/x)')) 285 #exec(),能處理男的eval()。例如迴圈 286 def Fibonacci_test_again(TIME): 287 x,y, = 0,1 288 while TIME>0: 289 yield y 290 x,y = y,x+y 291 TIME-=1 292 return 'Over maximum.' 293 g = Fibonacci_test_again(10) 294 while True: 295 try: 296 x= next(g) 297 print('g:',x) 298 except StopIteration as e: 299 print("Generator return value:",e.value) 300 break 301 #lambda,匿名函式。 302 (lambda n:print('n:',n))(5) 303 cal = lambda n:n 304 print('n:',cal(5)) 305 (lambda n:print('n大於2時n等於',1) if n>2 else print('n小於等於2時n等於',5))(3)#三元運算 306 #frozenset()返回一個凍結的集合,凍結後集合不能再新增或刪除任何元素 307 set_test = frozenset([1,2,3,4,5,6,3,4,87,6]) 308 print(set_test) 309 #globals(),返回整個檔案的變數的key-value,變數名key,內容是value. 310 print(globals()) 311 #hash(),給輸入的資料弄一個對映關係。用於獲取取一個物件(字串或者數值等)的雜湊值 312 hash_test= hash('test') 313 print(hash_test,hash(1)) 314 #hex(),將10進位制轉化為16進位制。 315 print(hex(10),hex(11),hex(12),hex(13),hex(14)) 316 #isinstance,函式來判斷一個物件是否是一個已知的型別,類似 type()。 317 # isinstance() 與 type() 區別:type() 不會認為子類是一種父類型別,不考慮繼承關係。isinstance() 會認為子類是一種父類型別, 318 # 考慮繼承關係。如果要判斷兩個型別是否相同推薦使用 isinstance()。 319 number = 5 320 str_test = 'test' 321 number_type =int 322 str_type = str 323 print(isinstance(number,number_type)) 324 print(type(str_test)) 325 #print(isinstance(str_test,str_type))#不曉得為啥子不行的 326 #id(),返回記憶體地址。 327 print(id(number)) 328 print(id(str_test)) 329 #locals() 函式會以字典型別返回當前位置的全部區域性變數。對於函式, 方法, lambda 函式, 類, 以及實現了 __call__ 方法的類例項, 330 # 它都返回 True。 331 def causal_test(*args): 332 z = args 333 print(locals()) 334 causal_test(5) 335 print(locals()) 336 print(globals()) 337 #max(),返回列表最大值。 338 list_test = [1,2,3,4,59,7,75,3,2,] 339 print(max(list_test)) 340 #oct(),函式將一個整數轉換成8進位制字串。 341 print(oct(number)) 342 print(oct(1),oct(2),oct(3),oct(4),oct(5),oct(6),oct(8),oct(9),oct(9),oct(10)) 343 #pow(),x的n次方。 344 print(pow(3,3)) 345 #repr(),與ascii類似。將物件轉化為供直譯器讀取的形式 346 print(repr('test')) 347 print(repr({'one':1,"two":2})) 348 #round()方法返回浮點數X的四捨五入值。 349 print(round(8.564)) 350 print(round(8.464)) 351 #slice(),函式實現切片物件,主要用在切片操作函式裡的引數傳遞。 352 circulation = range(10) 353 cut = slice(5) 354 print(cut) 355 print(circulation) 356 print(circulation[cut]) 357 #sorted(),可以給dictionary排序。 358 #sort與sorted區別:sort是應用在list上的方法,sorted可以對所有可迭代的物件進行排序操作。list 的 sort 方法返回的是對已經存在 359 #的列表進行操作,無返回值,而內建函式 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。 360 list = [5,6,4,7,6,1,2,5,6,4] 361 print(list) 362 list.sort() 363 print(list) 364 dictionary_test = {1:'a',2:'b',8:'d',4:'c',5:'e'} 365 print(sorted(dictionary_test.items())) 366 print(sorted(dictionary_test.items(),key = lambda y:y[1])) 367 print(sorted(dictionary_test.items(),key = lambda y:y[1],reverse = True)) 368 #vars(),返回一個物件的所有屬性名 369 #zip(),拼接 370 A_number = [0,1,2,3,4,5] 371 A_english = ['zero','one','two','three','four','five'] 372 for i in zip(A_number,A_english): 373 print(i) 374 #_import___import__() 函式用於動態載入類和函式 。如果一個模組經常變化就可以使用 __import__() 來動態載入。 375 #json序列化,所謂的序列化也就是將記憶體物件變為字串 376 import json 377 info = { 378 "name":'souce', 379 'age':23 380 } 381 f = open("test.test",'w') 382 f.write(json.dumps(info)) 383 f.close() 384 f = open("test.test",'r') 385 data = json.loads(f.read()) 386 print(data['age']) 387 #有__init__的叫做包 388 # 1、json.dumps()和json.loads()是json格式處理函式(可以這麼理解,json是字串) 389 #   (1)json.dumps()函式是將一個Python資料型別列表進行json格式的編碼(可以這麼理解,json.dumps()函式是將字典轉化為字串) 390 #   (2)json.loads()函式是將json格式資料轉換為字典(可以這麼理解,json.loads()函式是將字串轉化為字典) 391 # 2、json.dump()和json.load()主要用來讀寫json檔案函式