學習筆記之X分鐘速成Python3

X分鐘速成Python3python

  1 # 用井字符開頭的是單行註釋
  2 
  3 """ 多行字符串用三個引號
  4     包裹,也常被用來作多
  5     行註釋
  6 """
  7 
  8 ####################################################
  9 ## 1. 原始數據類型和運算符
 10 ####################################################
 11 
 12 # 整數
 13 3  # => 3
 14 
 15 # 算術沒有什麼出乎意料的
 16 1 + 1  # => 2
 17 8 - 1  # => 7
 18 10 * 2  # => 20
 19 
 20 # 可是除法例外,會自動轉換成浮點數
 21 35 / 5  # => 7.0
 22 5 / 3  # => 1.6666666666666667
 23 
 24 # 整數除法的結果都是向下取整
 25 5 // 3     # => 1
 26 5.0 // 3.0 # => 1.0 # 浮點數也能夠
 27 -5 // 3  # => -2
 28 -5.0 // 3.0 # => -2.0
 29 
 30 # 浮點數的運算結果也是浮點數
 31 3 * 2.0 # => 6.0
 32 
 33 # 模除
 34 7 % 3 # => 1
 35 
 36 # x的y次方
 37 2**4 # => 16
 38 
 39 # 用括號決定優先級
 40 (1 + 3) * 2  # => 8
 41 
 42 # 布爾值
 43 True
 44 False
 45 
 46 # 用not取非
 47 not True  # => False
 48 not False  # => True
 49 
 50 # 邏輯運算符,注意and和or都是小寫
 51 True and False # => False
 52 False or True # => True
 53 
 54 # 整數也能夠看成布爾值
 55 0 and 2 # => 0
 56 -5 or 0 # => -5
 57 0 == False # => True
 58 2 == True # => False
 59 1 == True # => True
 60 
 61 # 用==判斷相等
 62 1 == 1  # => True
 63 2 == 1  # => False
 64 
 65 # 用!=判斷不等
 66 1 != 1  # => False
 67 2 != 1  # => True
 68 
 69 # 比較大小
 70 1 < 10  # => True
 71 1 > 10  # => False
 72 2 <= 2  # => True
 73 2 >= 2  # => True
 74 
 75 # 大小比較能夠連起來!
 76 1 < 2 < 3  # => True
 77 2 < 3 < 2  # => False
 78 
 79 # 字符串用單引雙引均可以
 80 "這是個字符串"
 81 '這也是個字符串'
 82 
 83 # 用加號鏈接字符串
 84 "Hello " + "world!"  # => "Hello world!"
 85 
 86 # 字符串能夠被看成字符列表
 87 "This is a string"[0]  # => 'T'
 88 
 89 # 用.format來格式化字符串
 90 "{} can be {}".format("strings", "interpolated")
 91 
 92 # 能夠重複參數以節省時間
 93 "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
 94 # => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
 95 
 96 # 若是不想數參數,能夠用關鍵字
 97 "{name} wants to eat {food}".format(name="Bob", food="lasagna") 
 98 # => "Bob wants to eat lasagna"
 99 
100 # 若是你的Python3程序也要在Python2.5如下環境運行,也能夠用老式的格式化語法
101 "%s can be %s the %s way" % ("strings", "interpolated", "old")
102 
103 # None是一個對象
104 None  # => None
105 
106 # 當與None進行比較時不要用 ==,要用is。is是用來比較兩個變量是否指向同一個對象。
107 "etc" is None  # => False
108 None is None  # => True
109 
110 # None,0,空字符串,空列表,空字典都算是False
111 # 全部其餘值都是True
112 bool(0)  # => False
113 bool("")  # => False
114 bool([]) # => False
115 bool({}) # => False
116 
117 
118 ####################################################
119 ## 2. 變量和集合
120 ####################################################
121 
122 # print是內置的打印函數
123 print("I'm Python. Nice to meet you!")
124 
125 # 在給變量賦值前不用提早聲明
126 # 傳統的變量命名是小寫,用下劃線分隔單詞
127 some_var = 5
128 some_var  # => 5
129 
130 # 訪問未賦值的變量會拋出異常
131 # 參考流程控制一段來學習異常處理
132 some_unknown_var  # 拋出NameError
133 
134 # 用列表(list)儲存序列
135 li = []
136 # 建立列表時也能夠同時賦給元素
137 other_li = [4, 5, 6]
138 
139 # 用append在列表最後追加元素
140 li.append(1)    # li如今是[1]
141 li.append(2)    # li如今是[1, 2]
142 li.append(4)    # li如今是[1, 2, 4]
143 li.append(3)    # li如今是[1, 2, 4, 3]
144 # 用pop從列表尾部刪除
145 li.pop()        # => 3 且li如今是[1, 2, 4]
146 # 把3再放回去
147 li.append(3)    # li變回[1, 2, 4, 3]
148 
149 # 列表存取跟數組同樣
150 li[0]  # => 1
151 # 取出最後一個元素
152 li[-1]  # => 3
153 
154 # 越界存取會形成IndexError
155 li[4]  # 拋出IndexError
156 
157 # 列表有切割語法
158 li[1:3]  # => [2, 4]
159 # 取尾
160 li[2:]  # => [4, 3]
161 # 取頭
162 li[:3]  # => [1, 2, 4]
163 # 隔一個取一個
164 li[::2]   # =>[1, 4]
165 # 倒排列表
166 li[::-1]   # => [3, 4, 2, 1]
167 # 能夠用三個參數的任何組合來構建切割
168 # li[始:終:步伐]
169 
170 # 用del刪除任何一個元素
171 del li[2]   # li is now [1, 2, 3]
172 
173 # 列表能夠相加
174 # 注意:li和other_li的值都不變
175 li + other_li   # => [1, 2, 3, 4, 5, 6]
176 
177 # 用extend拼接列表
178 li.extend(other_li)   # li如今是[1, 2, 3, 4, 5, 6]
179 
180 # 用in測試列表是否包含值
181 1 in li   # => True
182 
183 # 用len取列表長度
184 len(li)   # => 6
185 
186 
187 # 元組是不可改變的序列
188 tup = (1, 2, 3)
189 tup[0]   # => 1
190 tup[0] = 3  # 拋出TypeError
191 
192 # 列表容許的操做元組大均可以
193 len(tup)   # => 3
194 tup + (4, 5, 6)   # => (1, 2, 3, 4, 5, 6)
195 tup[:2]   # => (1, 2)
196 2 in tup   # => True
197 
198 # 能夠把元組合列表解包,賦值給變量
199 a, b, c = (1, 2, 3)     # 如今a是1,b是2,c是3
200 # 元組周圍的括號是能夠省略的
201 d, e, f = 4, 5, 6
202 # 交換兩個變量的值就這麼簡單
203 e, d = d, e     # 如今d是5,e是4
204 
205 
206 # 用字典表達映射關係
207 empty_dict = {}
208 # 初始化的字典
209 filled_dict = {"one": 1, "two": 2, "three": 3}
210 
211 # 用[]取值
212 filled_dict["one"]   # => 1
213 
214 
215 # 用 keys 得到全部的鍵。
216 # 由於 keys 返回一個可迭代對象,因此在這裏把結果包在 list 裏。咱們下面會詳細介紹可迭代。
217 # 注意:字典鍵的順序是不定的,你獲得的結果可能和如下不一樣。
218 list(filled_dict.keys())   # => ["three", "two", "one"]
219 
220 
221 # 用values得到全部的值。跟keys同樣,要用list包起來,順序也可能不一樣。
222 list(filled_dict.values())   # => [3, 2, 1]
223 
224 
225 # 用in測試一個字典是否包含一個鍵
226 "one" in filled_dict   # => True
227 1 in filled_dict   # => False
228 
229 # 訪問不存在的鍵會致使KeyError
230 filled_dict["four"]   # KeyError
231 
232 # 用get來避免KeyError
233 filled_dict.get("one")   # => 1
234 filled_dict.get("four")   # => None
235 # 當鍵不存在的時候get方法能夠返回默認值
236 filled_dict.get("one", 4)   # => 1
237 filled_dict.get("four", 4)   # => 4
238 
239 # setdefault方法只有當鍵不存在的時候插入新值
240 filled_dict.setdefault("five", 5)  # filled_dict["five"]設爲5
241 filled_dict.setdefault("five", 6)  # filled_dict["five"]仍是5
242 
243 # 字典賦值
244 filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
245 filled_dict["four"] = 4  # 另外一種賦值方法
246 
247 # 用del刪除
248 del filled_dict["one"]  # 從filled_dict中把one刪除
249 
250 
251 # 用set表達集合
252 empty_set = set()
253 # 初始化一個集合,語法跟字典類似。
254 some_set = {1, 1, 2, 2, 3, 4}   # some_set如今是{1, 2, 3, 4}
255 
256 # 能夠把集合賦值於變量
257 filled_set = some_set
258 
259 # 爲集合添加元素
260 filled_set.add(5)   # filled_set如今是{1, 2, 3, 4, 5}
261 
262 # & 取交集
263 other_set = {3, 4, 5, 6}
264 filled_set & other_set   # => {3, 4, 5}
265 
266 # | 取並集
267 filled_set | other_set   # => {1, 2, 3, 4, 5, 6}
268 
269 # - 取補集
270 {1, 2, 3, 4} - {2, 3, 5}   # => {1, 4}
271 
272 # in 測試集合是否包含元素
273 2 in filled_set   # => True
274 10 in filled_set   # => False
275 
276 
277 ####################################################
278 ## 3. 流程控制和迭代器
279 ####################################################
280 
281 # 先隨便定義一個變量
282 some_var = 5
283 
284 # 這是個if語句。注意縮進在Python裏是有意義的
285 # 印出"some_var比10小"
286 if some_var > 10:
287     print("some_var比10大")
288 elif some_var < 10:    # elif句是可選的
289     print("some_var比10小")
290 else:                  # else也是可選的
291     print("some_var就是10")
292 
293 
294 """
295 用for循環語句遍歷列表
296 打印:
297     dog is a mammal
298     cat is a mammal
299     mouse is a mammal
300 """
301 for animal in ["dog", "cat", "mouse"]:
302     print("{} is a mammal".format(animal))
303 
304 """
305 "range(number)"返回數字列表從0到給的數字
306 打印:
307     0
308     1
309     2
310     3
311 """
312 for i in range(4):
313     print(i)
314 
315 """
316 while循環直到條件不知足
317 打印:
318     0
319     1
320     2
321     3
322 """
323 x = 0
324 while x < 4:
325     print(x)
326     x += 1  # x = x + 1 的簡寫
327 
328 # 用try/except塊處理異常情況
329 try:
330     # 用raise拋出異常
331     raise IndexError("This is an index error")
332 except IndexError as e:
333     pass    # pass是無操做,可是應該在這裏處理錯誤
334 except (TypeError, NameError):
335     pass    # 能夠同時處理不一樣類的錯誤
336 else:   # else語句是可選的,必須在全部的except以後
337     print("All good!")   # 只有當try運行完沒有錯誤的時候這句纔會運行
338 
339 
340 # Python提供一個叫作可迭代(iterable)的基本抽象。一個可迭代對象是能夠被看成序列
341 # 的對象。好比說上面range返回的對象就是可迭代的。
342 
343 filled_dict = {"one": 1, "two": 2, "three": 3}
344 our_iterable = filled_dict.keys()
345 print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一個實現可迭代接口的對象
346 
347 # 可迭代對象能夠遍歷
348 for i in our_iterable:
349     print(i)    # 打印 one, two, three
350 
351 # 可是不能夠隨機訪問
352 our_iterable[1]  # 拋出TypeError
353 
354 # 可迭代對象知道怎麼生成迭代器
355 our_iterator = iter(our_iterable)
356 
357 # 迭代器是一個能夠記住遍歷的位置的對象
358 # 用__next__能夠取得下一個元素
359 our_iterator.__next__()  # => "one"
360 
361 # 再一次調取__next__時會記得位置
362 our_iterator.__next__()  # => "two"
363 our_iterator.__next__()  # => "three"
364 
365 # 當迭代器全部元素都取出後,會拋出StopIteration
366 our_iterator.__next__() # 拋出StopIteration
367 
368 # 能夠用list一次取出迭代器全部的元素
369 list(filled_dict.keys())  # => Returns ["one", "two", "three"]
370 
371 
372 
373 ####################################################
374 ## 4. 函數
375 ####################################################
376 
377 # 用def定義新函數
378 def add(x, y):
379     print("x is {} and y is {}".format(x, y))
380     return x + y    # 用return語句返回
381 
382 # 調用函數
383 add(5, 6)   # => 印出"x is 5 and y is 6"而且返回11
384 
385 # 也能夠用關鍵字參數來調用函數
386 add(y=6, x=5)   # 關鍵字參數能夠用任何順序
387 
388 
389 # 咱們能夠定義一個可變參數函數
390 def varargs(*args):
391     return args
392 
393 varargs(1, 2, 3)   # => (1, 2, 3)
394 
395 
396 # 咱們也能夠定義一個關鍵字可變參數函數
397 def keyword_args(**kwargs):
398     return kwargs
399 
400 # 咱們來看看結果是什麼:
401 keyword_args(big="foot", loch="ness")   # => {"big": "foot", "loch": "ness"}
402 
403 
404 # 這兩種可變參數能夠混着用
405 def all_the_args(*args, **kwargs):
406     print(args)
407     print(kwargs)
408 """
409 all_the_args(1, 2, a=3, b=4) prints:
410     (1, 2)
411     {"a": 3, "b": 4}
412 """
413 
414 # 調用可變參數函數時能夠作跟上面相反的,用*展開序列,用**展開字典。
415 args = (1, 2, 3, 4)
416 kwargs = {"a": 3, "b": 4}
417 all_the_args(*args)   # 至關於 foo(1, 2, 3, 4)
418 all_the_args(**kwargs)   # 至關於 foo(a=3, b=4)
419 all_the_args(*args, **kwargs)   # 至關於 foo(1, 2, 3, 4, a=3, b=4)
420 
421 
422 # 函數做用域
423 x = 5
424 
425 def setX(num):
426     # 局部做用域的x和全局域的x是不一樣的
427     x = num # => 43
428     print (x) # => 43
429 
430 def setGlobalX(num):
431     global x
432     print (x) # => 5
433     x = num # 如今全局域的x被賦值
434     print (x) # => 6
435 
436 setX(43)
437 setGlobalX(6)
438 
439 
440 # 函數在Python是一等公民
441 def create_adder(x):
442     def adder(y):
443         return x + y
444     return adder
445 
446 add_10 = create_adder(10)
447 add_10(3)   # => 13
448 
449 # 也有匿名函數
450 (lambda x: x > 2)(3)   # => True
451 
452 # 內置的高階函數
453 map(add_10, [1, 2, 3])   # => [11, 12, 13]
454 filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]
455 
456 # 用列表推導式能夠簡化映射和過濾。列表推導式的返回值是另外一個列表。
457 [add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]
458 [x for x in [3, 4, 5, 6, 7] if x > 5]   # => [6, 7]
459 
460 ####################################################
461 ## 5. 類
462 ####################################################
463 
464 
465 # 定義一個繼承object的類
466 class Human(object):
467 
468     # 類屬性,被全部此類的實例共用。
469     species = "H. sapiens"
470 
471     # 構造方法,當實例被初始化時被調用。注意名字先後的雙下劃線,這是代表這個屬
472     # 性或方法對Python有特殊意義,可是容許用戶自行定義。你本身取名時不該該用這
473     # 種格式。
474     def __init__(self, name):
475         # Assign the argument to the instance's name attribute
476         self.name = name
477 
478     # 實例方法,第一個參數老是self,就是這個實例對象
479     def say(self, msg):
480         return "{name}: {message}".format(name=self.name, message=msg)
481 
482     # 類方法,被全部此類的實例共用。第一個參數是這個類對象。
483     @classmethod
484     def get_species(cls):
485         return cls.species
486 
487     # 靜態方法。調用時沒有實例或類的綁定。
488     @staticmethod
489     def grunt():
490         return "*grunt*"
491 
492 
493 # 構造一個實例
494 i = Human(name="Ian")
495 print(i.say("hi"))     # 印出 "Ian: hi"
496 
497 j = Human("Joel")
498 print(j.say("hello"))  # 印出 "Joel: hello"
499 
500 # 調用一個類方法
501 i.get_species()   # => "H. sapiens"
502 
503 # 改一個共用的類屬性
504 Human.species = "H. neanderthalensis"
505 i.get_species()   # => "H. neanderthalensis"
506 j.get_species()   # => "H. neanderthalensis"
507 
508 # 調用靜態方法
509 Human.grunt()   # => "*grunt*"
510 
511 
512 ####################################################
513 ## 6. 模塊
514 ####################################################
515 
516 # 用import導入模塊
517 import math
518 print(math.sqrt(16))  # => 4.0
519 
520 # 也能夠從模塊中導入個別值
521 from math import ceil, floor
522 print(ceil(3.7))  # => 4.0
523 print(floor(3.7))   # => 3.0
524 
525 # 能夠導入一個模塊中全部值
526 # 警告:不建議這麼作
527 from math import *
528 
529 # 如此縮寫模塊名字
530 import math as m
531 math.sqrt(16) == m.sqrt(16)   # => True
532 
533 # Python模塊其實就是普通的Python文件。你能夠本身寫,而後導入,
534 # 模塊的名字就是文件的名字。
535 
536 # 你能夠這樣列出一個模塊裏全部的值
537 import math
538 dir(math)
539 
540 
541 ####################################################
542 ## 7. 高級用法
543 ####################################################
544 
545 # 用生成器(generators)方便地寫惰性運算
546 def double_numbers(iterable):
547     for i in iterable:
548         yield i + i
549 
550 # 生成器只有在須要時才計算下一個值。它們每一次循環只生成一個值,而不是把全部的
551 # 值所有算好。
552 #
553 # range的返回值也是一個生成器,否則一個1到900000000的列表會花不少時間和內存。
554 #
555 # 若是你想用一個Python的關鍵字看成變量名,能夠加一個下劃線來區分。
556 range_ = range(1, 900000000)
557 # 當找到一個 >=30 的結果就會停
558 # 這意味着 `double_numbers` 不會生成大於30的數。
559 for i in double_numbers(range_):
560     print(i)
561     if i >= 30:
562         break
563 
564 
565 # 裝飾器(decorators)
566 # 這個例子中,beg裝飾say
567 # beg會先調用say。若是返回的say_please爲真,beg會改變返回的字符串。
568 from functools import wraps
569 
570 
571 def beg(target_function):
572     @wraps(target_function)
573     def wrapper(*args, **kwargs):
574         msg, say_please = target_function(*args, **kwargs)
575         if say_please:
576             return "{} {}".format(msg, "Please! I am poor :(")
577         return msg
578 
579     return wrapper
580 
581 
582 @beg
583 def say(say_please=False):
584     msg = "Can you buy me a beer?"
585     return msg, say_please
586 
587 
588 print(say())  # Can you buy me a beer?
589 print(say(say_please=True))  # Can you buy me a beer? Please! I am poor :(
View Code

 

1. 原始數據類型和運算符

  • # 可是除法例外,會自動轉換成浮點數
    • 35 / 5 # => 7.0
    • 5 / 3 # => 1.6666666666666667
  • # 整數除法的結果都是向下取整
    • 5 // 3 # => 1
    • 5.0 // 3.0 # => 1.0 # 浮點數也能夠
    • -5 // 3 # => -2
    • -5.0 // 3.0 # => -2.0
  • # 整數也能夠看成布爾值
    • 0 and 2 # => 0
    • -5 or 0 # => -5
    • 0 == False # => True
    • 2 == True # => False
    • 1 == True # => True
  • # 大小比較能夠連起來!
    • 1 < 2 < 3 # => True
    • 2 < 3 < 2 # => False
  • # 字符串能夠被看成字符列表
    • "This is a string"[0] # => 'T'
  • # 若是不想數參數,能夠用關鍵字
    • "{name} wants to eat {food}".format(name="Bob", food="lasagna")
    • # => "Bob wants to eat lasagna"
  • # None是一個對象
    • None # => None
  • # None,0,空字符串,空列表,空字典都算是False
  • # 全部其餘值都是True
    • bool(0) # => False
    • bool("") # => False
    • bool([]) # => False
    • bool({}) # => False

2. 變量和集合

  • # 訪問未賦值的變量會拋出異常
  • # 參考流程控制一段來學習異常處理
    • some_unknown_var # 拋出NameError
  • # 越界存取會形成IndexError
    • li[4] # 拋出IndexError
  • # 隔一個取一個
    • li[::2] # =>[1, 4]
  • # 倒排列表
    • li[::-1] # => [3, 4, 2, 1]
  • # 能夠用三個參數的任何組合來構建切割
    • # li[始:終:步伐]
  • # 用extend拼接列表
    • li.extend(other_li) # li如今是[1, 2, 3, 4, 5, 6]
  • # 元組是不可改變的序列
    • tup = (1, 2, 3)
    • tup[0] # => 1
    • tup[0] = 3 # 拋出TypeError
  • # 能夠把元組合列表解包,賦值給變量
    • a, b, c = (1, 2, 3) # 如今a是1,b是2,c是3
  • # 元組周圍的括號是能夠省略的
    • d, e, f = 4, 5, 6
  • # 交換兩個變量的值就這麼簡單
    • e, d = d, e # 如今d是5,e是4
  • # 用 keys 得到全部的鍵。
  • # 由於 keys 返回一個可迭代對象,因此在這裏把結果包在 list 裏。咱們下面會詳細介紹可迭代。
  • # 注意:字典鍵的順序是不定的,你獲得的結果可能和如下不一樣。
    • list(filled_dict.keys()) # => ["three", "two", "one"]
  • # 用values得到全部的值。跟keys同樣,要用list包起來,順序也可能不一樣。
    • list(filled_dict.values()) # => [3, 2, 1]
  • # 訪問不存在的鍵會致使KeyError
    • filled_dict["four"] # KeyError
  • # 用get來避免KeyError
    • filled_dict.get("one") # => 1
    • filled_dict.get("four") # => None
  • # 當鍵不存在的時候get方法能夠返回默認值
    • filled_dict.get("one", 4) # => 1
    • filled_dict.get("four", 4) # => 4
  • # setdefault方法只有當鍵不存在的時候插入新值
    • filled_dict.setdefault("five", 5) # filled_dict["five"]設爲5
    • filled_dict.setdefault("five", 6) # filled_dict["five"]仍是5
  • # 字典賦值
    • filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
    • filled_dict["four"] = 4 # 另外一種賦值方法
  • # 用del刪除
    • del filled_dict["one"] # 從filled_dict中把one刪除
  • # 用set表達集合
    • empty_set = set()
  • # 初始化一個集合,語法跟字典類似。
    • some_set = {1, 1, 2, 2, 3, 4} # some_set如今是{1, 2, 3, 4}
  • # 爲集合添加元素
    • filled_set.add(5) # filled_set如今是{1, 2, 3, 4, 5}
  • # & 取交集
    • other_set = {3, 4, 5, 6}
    • filled_set & other_set # => {3, 4, 5}
  • # | 取並集
    • filled_set | other_set # => {1, 2, 3, 4, 5, 6}
  • # - 取補集
    • {1, 2, 3, 4} - {2, 3, 5} # => {1, 4}

3. 流程控制和迭代器

  • # 用try/except塊處理異常情況
    • try:
    • # 用raise拋出異常
      • raise IndexError("This is an index error")
    • except IndexError as e:
      • pass # pass是無操做,可是應該在這裏處理錯誤
    • except (TypeError, NameError):
      • pass # 能夠同時處理不一樣類的錯誤
    • else: # else語句是可選的,必須在全部的except以後
      • print("All good!") # 只有當try運行完沒有錯誤的時候這句纔會運行
  • # Python提供一個叫作可迭代(iterable)的基本抽象。一個可迭代對象是能夠被看成序列
  • # 的對象。好比說上面range返回的對象就是可迭代的。
    • filled_dict = {"one": 1, "two": 2, "three": 3}
    • our_iterable = filled_dict.keys()
    • print(our_iterable) # => dict_keys(['one', 'two', 'three']),是一個實現可迭代接口的對象
  • # 可迭代對象能夠遍歷
    • for i in our_iterable:
      • print(i) # 打印 one, two, three
  • # 可是不能夠隨機訪問
    • our_iterable[1] # 拋出TypeError
  • # 可迭代對象知道怎麼生成迭代器
    • our_iterator = iter(our_iterable)
  • # 迭代器是一個能夠記住遍歷的位置的對象
  • # 用__next__能夠取得下一個元素
    • our_iterator.__next__() # => "one"
  • # 再一次調取__next__時會記得位置
    • our_iterator.__next__() # => "two"
    • our_iterator.__next__() # => "three"
  • # 當迭代器全部元素都取出後,會拋出StopIteration
    • our_iterator.__next__() # 拋出StopIteration
  • # 能夠用list一次取出迭代器全部的元素
    • list(filled_dict.keys()) # => Returns ["one", "two", "three"]

4. 函數

  • # 也能夠用關鍵字參數來調用函數
    • add(y=6, x=5) # 關鍵字參數能夠用任何順序
  • # 咱們能夠定義一個可變參數函數
    • def varargs(*args):
      • return args
    • varargs(1, 2, 3) # => (1, 2, 3)
  • # 咱們也能夠定義一個關鍵字可變參數函數
    • def keyword_args(**kwargs):
      • return kwargs
  • # 咱們來看看結果是什麼:
    • keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
  • # 這兩種可變參數能夠混着用
    • def all_the_args(*args, **kwargs):
      • print(args)
      • print(kwargs)
    • """
    • all_the_args(1, 2, a=3, b=4) prints:
    • (1, 2)
    • {"a": 3, "b": 4}
    • """
  • # 調用可變參數函數時能夠作跟上面相反的,用*展開序列,用**展開字典。
    • args = (1, 2, 3, 4)
    • kwargs = {"a": 3, "b": 4}
    • all_the_args(*args) # 至關於 foo(1, 2, 3, 4)
    • all_the_args(**kwargs) # 至關於 foo(a=3, b=4)
    • all_the_args(*args, **kwargs) # 至關於 foo(1, 2, 3, 4, a=3, b=4)
  • # 函數做用域
    • x = 5
    • def setX(num):
      • # 局部做用域的x和全局域的x是不一樣的
      • x = num # => 43
      • print (x) # => 43
    • def setGlobalX(num):
      • global x
      • print (x) # => 5
      • x = num # 如今全局域的x被賦值
      • print (x) # => 6
    • setX(43)
    • setGlobalX(6)
  • # 函數在Python是一等公民
    • def create_adder(x):
      • def adder(y):
        • return x + y
      • return adder
    • add_10 = create_adder(10)
    • add_10(3) # => 13
  • # 也有匿名函數
    • (lambda x: x > 2)(3) # => True
  • # 內置的高階函數
    • map(add_10, [1, 2, 3]) # => [11, 12, 13]
    • filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
  • # 用列表推導式能夠簡化映射和過濾。列表推導式的返回值是另外一個列表。
    • [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
    • [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]

5. 類

  • # 定義一個繼承object的類
    • class Human(object):
      • # 類屬性,被全部此類的實例共用。
        • species = "H. sapiens"
      • # 構造方法,當實例被初始化時被調用。注意名字先後的雙下劃線,這是代表這個屬性或方法對Python有特殊意義,可是容許用戶自行定義。你本身取名時不該該用這種格式。
        • def __init__(self, name):
        • # Assign the argument to the instance's name attribute
          • self.name = name
      • # 實例方法,第一個參數老是self,就是這個實例對象
        • def say(self, msg):
          • return "{name}: {message}".format(name=self.name, message=msg)
      • # 類方法,被全部此類的實例共用。第一個參數是這個類對象。
        • @classmethod
        • def get_species(cls):
          • return cls.species
      • # 靜態方法。調用時沒有實例或類的綁定。
        • @staticmethod
        • def grunt():
          • return "*grunt*"
  • # 構造一個實例
    • i = Human(name="Ian")
    • print(i.say("hi")) # 印出 "Ian: hi"
    • j = Human("Joel")
    • print(j.say("hello")) # 印出 "Joel: hello"
  • # 調用一個類方法
    • i.get_species() # => "H. sapiens"
  • # 改一個共用的類屬性
    • Human.species = "H. neanderthalensis"
    • i.get_species() # => "H. neanderthalensis"
    • j.get_species() # => "H. neanderthalensis"
  • # 調用靜態方法
    • Human.grunt() # => "*grunt*"

6. 模塊

  • # 你能夠這樣列出一個模塊裏全部的值
    • import math
    • dir(math)

7. 高級用法

  • # 用生成器(generators)方便地寫惰性運算
    • def double_numbers(iterable):
      • for i in iterable:
        • yield i + i
  • # 生成器只有在須要時才計算下一個值。它們每一次循環只生成一個值,而不是把全部的值所有算好。
  • # range的返回值也是一個生成器,否則一個1到90000的列表會花不少時間和內存。
  • # 若是你想用一個Python的關鍵字看成變量名,能夠加一個下劃線來區分。
    • range_ = range(1, 90000)
  • # 當找到一個 >=30 的結果就會停
  • # 這意味着 `double_numbers` 不會生成大於30的數。
    • for i in double_numbers(range_):
      • print(i)
      • if i >= 30:
        • break
  • # 裝飾器(decorators)
  • # 這個例子中,beg裝飾say
  • # beg會先調用say。若是返回的say_please爲真,beg會改變返回的字符串。
    • from functools import wraps
    • def beg(target_function):
      • @wraps(target_function)
      • def wrapper(*args, **kwargs):
        • msg, say_please = target_function(*args, **kwargs)
        • if say_please:
          • return "{} {}".format(msg, "Please! I am poor :(")
        • return msg
      • return wrapper
    • @beg
    • def say(say_please=False):
      • msg = "Can you buy me a beer?"
      • return msg, say_please
    • print(say()) # Can you buy me a beer?
    • print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
相關文章
相關標籤/搜索