1. 程式人生 > >7個案例15分鐘讓你瞭解Python套路!

7個案例15分鐘讓你瞭解Python套路!

古人云:書山有路勤為徑 學海無涯苦作舟 。

注:一般標榜著 “ XX天學會XX”、“ XX 分鐘瞭解XX”的文章都不會是讓你增長功力的文章,如本文。

隨著網際網路發展,全球在快速數字化,程式設計這件事也從數十年前只有科研人研在實驗室才能做的事變得越來越讓人們所熟悉。但是作為平時甚少接觸程式設計的小夥伴,是不是也會對計算機世界擁有一點點好奇心呢(比如電影《黑客帝國》、《原始碼》)?

Q1: "怎麼進入程式設計世界?"

首先,你要學會一門程式語言! 而我要推薦的計算機語言,答案已在標題中被出賣:Python! Python是一門十分容易上手,但是又被IT業界廣泛使用的程式語言(Scratch這種圖形化程式設計雖然簡單,但基本只能用於教學)。2016年5月份Python在全球最受歡迎程式語言中排第五。

Q2: “Python如何學?”

如果你是一位從未接觸過程式語言的新手,請移步 這裡。 此書作者是一位程式設計師大叔,大叔說了:“學程式設計,首先,得會打字!!不會打字您就別學了哈”。大叔的在書提出的觀點個人覺得也是值得學習的,無論用於程式設計還是其他事情,如:

As you study this book, and continue with programming, remember that anything worth doing is difficult at first. Maybe you are the kind of person who is afraid of failure so you give up at the first sign of difficulty. Maybe you never learned self-discipline so you can't do anything that's "boring." Maybe you were told that you are "gifted" so you never attempt anything that might make you seem stupid or not a prodigy. Maybe you are competitive and unfairly compare yourself to someone like me who's been programming for more than 20 years.

Whatever your reason for wanting to quit, keep at it. Force yourself. If you run into a Study Drill you can't do, or a lesson you just do not understand, then skip it and come back to it later. Just keep going because with programming there's this very odd thing that happens. At first, you will not understand anything. It'll be weird, just like with learning any human language. You will struggle with words, and not know what symbols are what, and it'll all be very confusing. Then one day BANG your brain will snap and you will suddenly "get it." If you keep doing the exercises and keep trying to understand them, you will get it. You might not be a master coder, but you will at least understand how programming works.”

萬事開頭難,但自己選擇的路,即使跪著也要走完。也許你是那種一碰到困難就想到放棄的人;也許你從未掌握“自律”這件事導致你無法做任何“枯燥”的事情;也許你一直被認為是“天才”,所以你不會傻到嘗試去做那些有可能讓你看起來是一個笨蛋或者至少不是“神童”的事情;也許你覺得和我這種已經程式設計超過20年的人比較程式設計這件事是一件逗逼的事情。

無論是什麼原因使你想要退出,不要管它!要管住自己(譯者注:論“自虐”能力的重要性。)! 如果某一個練習你不會做,或者有一課你聽不明白,那就跳過它,然後再回來重新學習(譯者注:子曰:溫故而知新)。程式設計這事說起來是件奇怪的事情,當你沒有領悟真諦的時候你只需要堅持。像學習任何一門自然語言一樣,剛開始時可能總會感覺怪怪的。那些奇怪的單詞,那些你不知道的符號,也許會讓你感到十分困惑。但只要你堅持不懈,堅持做本書中的那些練習並且嘗試著去理解它們。會有一天,你的腦子會突然閃出“哇哈~!原來是這樣!” 的頓悟時刻。也許你不會成為一個高階碼農,但是至少你將會知道程式設計到底是什麼鬼。

言歸正傳,本文面向物件為具有一丁點程式設計經驗的小夥伴,旨在快速瞭解Python的基本語法和部分特性。

前言

    # Python中單行註釋請用‘#’
    """ Python中多行註釋
        請用""",我寫不了那麼
        多字,隨便湊個樣板。
    """

1. 基本型別和運算子

    # 定義了一個數字 3
    3  # => 3

    # 基本計算
    1 + 1  # => 2
    8 - 1  # => 7
    10 * 2  # => 20
    35 / 5  # => 7

    # 當除數和被除數都為整型時,除 這個操作只求整數 
    # ( python2.x語法。經測試,Python3.x 已經全部當做浮點數處理,還會計算小數)
    5 / 2  # => 2
    10/-3 #python3的結果為-3.3333333333333335 python2 結果為-4
    10/3 #python3的結果為3.3333333333333335 python2 結果為3 
    #由上面兩個結果也可以看出,在Python2中,如結果有小數,則會取最近最小整數



    # 如果我們除數和被除數為浮點型,則Python會自動把結果儲存為浮點數
    2.0  # 這是浮點數
    11.0 / 4.0  # 這個時候結果就是2.75啦!是不是很神奇? 

    # 當用‘//’進行計算時,python3不會全部單做浮點數處理.
    5 // 3   # => 1
    5.0 // 3.0 # => 1.0 
    -5 // 3  # => -2
    -5.0 // 3.0 # => -2.0


    from __future__ import division # 注可以在通過 __future__  關鍵字
                                    # 在python2中引入python3 特性
    11/4    # => 2.75  ... 標準除法
    11//4   # => 2 ... 除後取整

    # 求餘數操作
    7 % 3 # => 1

    # 冪操作 2的4次方
    2**4 # => 16

    # 先乘除,後加減,口號優先
    (1 + 3) * 2  # => 8

    # 布林值操作
    # 注:or 和 and 兩個關鍵字是大小寫敏感的
    True and False #=> 返回False
    False or True #=> 返回True

    # 布林值和整形的關係,除了0外,其他都為真
    0 and 2 #=> 0
    -5 or 0 #=> -5
    0 == False #=> True
    2 == True #=> False
    1 == True #=> True

    #  not 操作
    not True  # => False
    not False  # => True

    #等值比較 “==”,相等返回值為True ,不相等返回False
    1 == 1  # => True
    2 == 1  # => False

    # 非等比較“!=”,如果兩個數不相等返回True,相等返回Flase
    1 != 1  # => False
    2 != 1  # => True

    # 大於/小於 和等於的組合比較
    1 < 10  # => True
    1 > 10  # => False
    2 <= 2  # => True
    2 >= 2  # => True

    # Python可以支援多數值進行組合比較,
           #但只要一個等值為False,則結果為False
    1 < 2 < 3  # => True
    2 < 3 < 2  # => False

    # 可以通過 " 或者 '來建立字串
    "This is a string."
    'This is also a string.'

    # 字串間可以通過 + 號進行相加,是不是簡單到爆?
    "Hello " + "world!"  # => "Hello world!"
    # 甚至不使用'+'號,也可以把字串進行連線
    "Hello " "world!"  # => "Hello world!"

     #可以通過 * 號,對字串進行復制,比如 ;
             importantNote = "重要的事情說三遍
" * 3 
             print (importantNote)
            """ 結果為:
             重要的事情說三遍
             重要的事情說三遍
             重要的事情說三遍
            """

    "Hello" * 3  # => "HelloHelloHello"

    # 字串可以在任意位置被打斷
    "This is a string"[0]  # => 'T'

    #字串可以用 %連線,並且可以打印出變數值
           #(和C/C++ 一樣%d 表示整數,%s表示字串,
           #但python可以自己進行判斷,我們無需太擔心這個問題)
    x = 'apple'
    y = 'lemon'
    z = "The items in the basket are %s and %s" % (x,y)

    # 一個新的更好的字串連線方式是通過.format()函式,推薦使用該方式
    "{} is a {}".format("This", "placeholder")
    "{0} can be {1}".format("strings", "formatted")
    # You can use keywords if you don't want to count.
    "{name} wants to eat {food}".format(name="Bob", food="lasagna")

    # None是一個物件,None就是None,它是一個特殊的變數
    None  # => None

    # 在和None進行比較時,不要用“==”操作符,用 “is”
    "etc" is None  # => False
    None is None  # => True


    #“is"操作符用於物件之間的比較,
            #對於底層型別進行比較時
    #不建議用“is”,但對於物件之間的比較,用“is”是最合適的
    # bool可以用於對任何物件進行判斷
    # 以下這些值是非真的
    #   - None
    #   - 各類數值型的0 (e.g., 0, 0L, 0.0, 0j)
    #   - 空元組、空列表 (e.g., '', (), [])
    #   - 空字典、空集合 (e.g., {}, set())
    #   - 其他值請參考:
    #     https://docs.python.org/2/reference/datamodel.html#object.__nonzero__
    #
    # All other values are truthy (using the bool() function on them returns True).
    bool(0)  # => False
    bool("")  # => False

2. 變數和集合

    # 列印 print()
    print ("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!

    # 從控制檯中獲取輸入
    input_string_var = raw_input("Enter some data: ") # 返回字串型別
    input_var = input("Enter some data: ") # python會判斷型別如果是字串 則輸入時要加“”or''
    # 注意:在 python 3中, input() 由 raw_input() 代替

    # 在Python中不需要設定變數型別,python會自動根據值進行判斷
    some_var = 5    
    some_var  # => 5


    # if 可以作為表達時被使用,下句可以這樣理解 “輸出‘yahool’如果3大於2的話,不然輸出2“
    "yahoo!" if 3 > 2 else 2  # => "yahoo!"

列表

    # python中的列表定義
    li = []
    # 也可以通過初始化時內建列表的值
    other_li = [4, 5, 6]

    # append函式可以在列表中插入值
    li.append(1)    # li is now [1]
    li.append(2)    # li is now [1, 2]
    li.append(4)    # li is now [1, 2, 4]
    li.append(3)    # li is now [1, 2, 4, 3]
    # pop函式從列表末移除值
    li.pop()        # => 3 and li is now [1, 2, 4]
    # 移除後通過append接回
    li.append(3)    # li is now [1, 2, 4, 3] again.

    # 通過[]的方式可以提取任何列表中的任意值
           #(前提,index不大於列表總數)
    li[0]  # => 1
    # 也可以通過[]下標的方式直接給列表賦值
    li[0] = 42
    li[0]  # => 42
    # 如果[]小標的值為負數,則表示以逆序獲取列表中的值
    li[-1]  # => 3

    # 查詢的值不可以超出列表個數,否則報錯。
    # 但是利用insert()插入時可以,超出範圍的值會直接被插入到列表最末
    li[4]  # Raises an IndexError

    # 可以通過[:],獲取列表中指定範圍的值
    # (It's a closed/open range for you mathy types.)
    # 這是半開取值法,比如li[1:3],取的是列表中index為1、2的兩個值,
    # 該法則適用於以下所有通過[]取值的方式
    li[1:3]  # => [2, 4]
    # 如果一邊不去值,則表示取所有該邊的值。
    li[2:]  # => [4, 3]
    li[:3]  # => [1, 2, 4]

    # [::2]表示選擇從[0]開始,步長為2上的值
    li[::2]   # =>[1, 4]
    # [::-1]表示反向選擇,-可以理解為 反向選擇,而1表示步長,步長1則包含了列表中的所有元素
    li[::-1]   # => [3, 4, 2, 1]
    # []規則完整版表示方法[開始:結束:步長]
    # li[start:end:step]

    #  "del"關鍵字可以直接刪除列表中的值
    del li[2]   # li is now [1, 2, 3]

    # 可以通過“+”操作符對列表進行操作,注:列表只有 + 操作,而集合(set)有+ 和 -
    li + other_li   # => [1, 2, 3, 4, 5, 6]


    # 也可以 "extend()"方法對列表進行擴充套件
    li.extend(other_li)   # Now li is [1, 2, 3, 4, 5, 6]

    # Remove 方法和 del 類似,但remove的直接是數值,而不是index
    li.remove(2)  # li is now [1, 3, 4, 5, 6]
    li.remove(2)  # 如果remove的值不存在列表中,則會報錯

    # 在指定位置插入數值,上面已經提過,如果index值超過的話,會直接插到列表末
    li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again

    # 獲取某個值的index
    li.index(2)  # => 1
    li.index(7)  # 如果

    # "in"可以直接檢視某個值是否存在於列表中
    1 in li   # => True

    # "len()"函式可以檢測佇列的數量
    len(li)   # => 6

元組

    # Tuples(元組)是一個類似數列的資料結構,但是元組是不可修改的
    tup = (1, 2, 3)
    tup[0]   # => 1
    tup[0] = 3  # 一修改就會報錯

    #數列中的方法在元組也可以使用(除了 修改)
    len(tup)   # => 3
    tup + (4, 5, 6)   # => (1, 2, 3, 4, 5, 6)
    tup[:2]   # => (1, 2)
    2 in tup   # => True

    # 可以一次性賦值幾個變數
    a, b, c = (1, 2, 3)  # a 為1,b為2,c為3
    d, e, f = 4, 5, 6      # 元組賦值也可以不用括號
    # 同樣元組不用括號也同樣可以建立
    g = 4, 5, 6          # => (4, 5, 6)
    # Python中的資料交換十分簡單:只要在賦值時互調位置即可
    e, d = d, e  # d is now 5 and e is now 4

字典

    # Python中的字典定義
    empty_dict = {}
    # 也可以通過定義時賦值給字典
    filled_dict = {"one": 1, "two": 2, "three": 3}

    # 可以通過[]的key方式查詢字典中的值
    filled_dict["one"]   # => 1

    # 可以通過"keys()"方法獲取字典中的所有key值
    filled_dict.keys()   # => ["three", "two", "one"]
    # Note - 返回的keys並不一定按照順序排列的.
    # 所以測試結果可能和上述結果不一致

    # 通過 "values()"的方式可以獲取字典中所有值,
     #同樣他們返回的結果也不一定按照順序排列
    filled_dict.values()   # => [3, 2, 1]


    # 可以通過 "in"方式獲取查詢某個鍵值是否存在字典中,但是數值不可以
    "one" in filled_dict   # => True
    1 in filled_dict   # => False

    # 查詢不存在的key值時,Python會報錯
    filled_dict["four"]   # KeyError

    #用 "get()" 方法可以避免鍵值錯誤的產生
    filled_dict.get("one")   # => 1
    filled_dict.get("four")   # => None
    # 當鍵值不存在的時候,get方法可以通過返回預設值,
    # 但是並沒有對值字典進行賦值
    filled_dict.get("one", 4)   # => 1
    filled_dict.get("four", 4)   # => 4


    # 字典中設定值的方式和列表類似,通過[]方式可以設定
    filled_dict["four"] = 4  # now, filled_dict["four"] => 4

    # "setdefault()" 可以設定字典中的值
    # 但是注意:只有當該鍵值之前未存在的時候,setdefault()函式才生效
    filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
    filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5

集合

    empty_set = set()
    # 初始化set的方式可以通過 set()來實現
    some_set = set([1, 2, 2, 3, 4])   # some_set is now set([1, 2, 3, 4])

    # 集合的排列是無序的!集合的排列是無序的!集合的排列是無序的!
    another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])

    # Python2.7以後,{}可以用於被定義集合
    filled_set = {1, 2, 2, 3, 4}   # => {1, 2, 3, 4}

    # Add方法可用於增加集合成員
    filled_set.add(5)   # filled_set is now {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}

    # 通過 ^ 操作符取非集
    {1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}

    # 通過 >= 判斷左邊集合是否是右邊集合的超集
    {1, 2} >= {1, 2, 3} # => False

    # 通過 <= 判斷左邊集合是否右邊集合的子集
    {1, 2} <= {1, 2, 3} # => True

    # 通過 in 可以判斷元素是否在集合中
    2 in filled_set   # => True
    10 in filled_set   # => False

Python資料集合型別總結

  • 列表 定義方式 li = [1,2,3,4,“Hello World”] (列表可以包含任意基本型別)

  • 元組 定義方式 tup = (1,2,3,4) (和列表類似,但 元組不可更改)

  • 字典 定義方式 dic = {“one”:2,“tow”:3,“three”:0}(字典,就是字典嘛。以 key:value 方式存在)

  • 集合 定義方式 set=set(1,2,3,4)or set = {1,2,3,4} (集合裡的元素是唯一的,集合支援 & | ^ + -操作)

3. Python 邏輯運算子

    # 建立一個變數
    some_var = 5

    # 通過if進行邏輯判斷
    if some_var > 10:
        print "some_var is totally bigger than 10."
    elif some_var < 10: # This elif clause is optional.
        print "some_var is smaller than 10."
    else:          # This is optional too.
        print "some_var is indeed 10."


    """
        通過for...in...進行迴圈列印:
        dog is a mammal
        cat is a mammal
        mouse is a mammal
    """
    for animal in ["dog", "cat", "mouse"]:
        # You can use {0} to interpolate formatted strings. (See above.)
        print "{0} is a mammal".format(animal)

    """
    通過"range()" 方式,控制for的迴圈次數
    prints:
        0
        1
        2
        3
    """
    for i in range(4):
        print i

    """
    "range(lower, upper)" 返回 lower 到 upper的值,
     注意:range左邊必須小於右邊引數
    prints:
        4
        5
        6
        7
    """
    for i in range(4, 8):
        print i

    """
    while 迴圈
    prints:
        0
        1
        2
        3
    """
    x = 0
    while x < 4:
        print x
        x += 1  # Shorthand for x = x + 1

    # Python支援 try/except 語法

    # Python2.6以上的版本,支援try...except...:
    try:
        # raise顯示地引發異常。一旦執行了raise語句,raise後面的語句將不能執行。
        raise IndexError("This is an index error")
    except IndexError as e:
        pass    # pass 空語句,跳過處理
    except (TypeError, NameError):
        pass    # python 支援同時檢測多個錯誤
    else:   # Python必須要處理所有情況,這裡是其他未定義的情況
        print "All good!"   
    finally: #  finally無論有沒有異常都會執行
        print "We can clean up resources here"

    #通過with函式,可以替代try....except...函式  [with詳解](http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/)
    with open("myfile.txt") as f:
        for line in f:
            print line

4. Functions

    # def 關鍵字定義函式
    def add(x, y):
        print "x is {0} and y is {1}".format(x, y)
        return x + y    #可以直接return結果

    # 函式呼叫引數
    add(5, 6)   # => prints out "x is 5 and y is 6" and returns 11

    # Python支援引數互換,只需要在呼叫函式時加上形參
    add(y=6, x=5)   # Keyword arguments can arrive in any order.


    # Python函式支援可變引數
    #  在定義函式時通過*號表示可變長引數
    def varargs(*args):
        return args

    varargs(1, 2, 3)   # => (1, 2, 3)

    # 可以通過**的方式定義Key可變長引數查詢字典中的關鍵詞

    def keyword_args(**kwargs):
        return kwargs

    # 當函式引數是**型別的時候,Python可以通過該函式定義字典
    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)   # equivalent to foo(1, 2, 3, 4)
    all_the_args(**kwargs)   # equivalent to foo(a=3, b=4)
    all_the_args(*args, **kwargs)   # equivalent to foo(1, 2, 3, 4, a=3, b=4)

    # 在函式中也可以通過單獨處理* 或者 **的方式,增加函式的健壯性
    def pass_all_the_args(*args, **kwargs):
        all_the_args(*args, **kwargs)
        print varargs(*args)
        print keyword_args(**kwargs)

    # 全域性變數 X
    x = 5

    def set_x(num):
        # 當在函式裡面改變變數時,如果沒有加gloabl關鍵字,則改變的是區域性變數
        x = num # => 43
        print x # => 43

    def set_global_x(num):
        global x
        print x # => 5
        x = num # 加了global關鍵字後,即可在函式內操作全域性變數
        print x # => 6

    set_x(43)
    set_global_x(6)

    # 返回函式指標方式定義函式/*換個說法,匿名函式*/
    def create_adder(x):
        def adder(y):
            return x + y
        return adder

    add_10 = create_adder(10)
    add_10(3)   # => 13

    # Lambda 關鍵字定義的匿名函式
    (lambda x: x > 2)(3)   # => True 
    (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5

    # map方式也可以呼叫函式並傳入引數
    map(add_10, [1, 2, 3])   # => [11, 12, 13]
    map(max, [1, 2, 3], [4, 2, 1])   # => [4, 2, 3]

    filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]

    # 可以通過這兩種方式結合呼叫,下面的函式解析:
    #add_10(i) 是映射了for...in...函式的返回值,返回值作為引數傳進。
    [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. Python中的類

    # 下面程式碼是定義了一個Human類,繼承自object類
    # Python類可以繼承自多個類,如class Human(object,orangOutang)
    class Human(object):

        # 類變數
        species = "H. sapiens"類介面
                    __species = "Other.sapiens" #內部結構,無法被外部直接訪問

        # __init__(),初始化函式,python中在對類進行處理時,會先處理以下函式,
        #其實就是系統預設定義了介面,而這個介面是開放給使用者去實現的,具體如下:   
        #__init__  建構函式,在生成物件時呼叫
        # __del__   解構函式,釋放物件時使用
        #__repr__ 列印,轉換
        #__setitem__按照索引賦值
        #__getitem__按照索引獲取值
        #__len__獲得長度
        #__cmp__比較運算
        #__call__函式呼叫
        #__add__加運算
        #__sub__減運算
        #__mul__乘運算
        #__div__除運算
        #__mod__求餘運算
        #__pow__稱方

        def __init__(self, name):
            #宣告類中的屬性,並初始化,在初始化的時候同時
            #就是定義了變數型別
            self.name = name
            self.age = 0

        # 在類中所有函式都必須把self作為第一個引數
        #(下面定義的類方法和靜態方法除外)
        def say(self, msg):
            return "{0}: {1}".format(self.name, msg)

        # 類方法
        @classmethod
        def get_species(cls):
            return cls.species

        # 靜態方法,
        @staticmethod
        def grunt():
            return "*grunt*"

        # A property is just like a getter.
        # It turns the method age() into an read-only attribute
        # of the same name.
        #property屬性,相當於getter
        @property
        def age(self):
            return self._age

        # This allows the property to be set
        @age.setter
        def age(self, age):
            self._age = age

        # This allows the property to be deleted
        @age.deleter
        def age(self):
            del self._age


    #類例項化
    i = Human(name="Ian")
    print i.say("hi")    # prints out "Ian: hi"

    j = Human("Joel")
    print j.say("hello")  # prints out "Joel: hello"

    #呼叫例項方法用"."
    i.get_species()   # => "H. sapiens"

    # 改變類變數
    Human.species = "H. neanderthalensis"
    i.get_species()   # => "H. neanderthalensis"
    j.get_species()   # => "H. neanderthalensis"

    # 呼叫靜態方法
    Human.grunt()   # => "*grunt*"

    # 給age賦值
    i.age = 42

    # 獲取age值
    i.age # => 42

    # 刪除age
    del i.age
    i.age  # => raises an AttributeError

6. Python的模組(庫)

    # Python中的一個*.py檔案就是一個模組
    import math
    print math.sqrt(16)  # => 4

    # 可以只引入模組中的某些類/方法
    from math import ceil, floor
    print ceil(3.7)  # => 4.0
    print floor(3.7)   # => 3.0

    # 也可以通過*引入全部方法
    # Warning: this is not recommended
    from math import *

    #math庫的縮寫可以為m
    math.sqrt(16) == m.sqrt(16)   # => True
    # 可以直接引入sqrt庫
    from math import sqrt
    math.sqrt == m.sqrt == sqrt  # => True



    #python的庫就只是檔案
    import math
    dir(math)

    # If you have a Python script named math.py in the same
    # folder as your current script, the file math.py will 
    # be loaded instead of the built-in Python module. 
    # This happens because the local folder has priority
    # over Python's built-in libraries. 

    #如果你在當前目錄下有一個Python指令碼的名字也叫math.py
    #當前目錄下的math.py會替換掉內建的Python模組
    #因為在Python中當前目錄的優先順序會高於內建模組的優先順序

7. Python中的高階特性(生成器、裝飾器:wraps)

    # Generators ,生成器函式在Python中與迭代器協議的概念聯絡在一起。
    # 簡而言之,包含yield語句的函式會被特地編譯成生成器。
    # 當函式被呼叫時,他們返回一個生成器物件,這個物件支援迭代器介面。函式        
    #也許會有個return語句,但它的作用是用來yield產生值的。
    for i in iterable:
        yield i + i

    xrange_ = xrange(1, 900000000)

    for i in double_numbers(xrange_):
        print i
        if i >= 30:
            break



    # 裝飾器wraps,wraps可以包裝
    # Beg will call say. If say_please is True then it will change the returned
    # message
    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 :

qun號是:八六四,六三四,八四五。qun內有很多開發工具,很多幹貨和技術資料分享!

如果您覺得此篇文章對您有幫助,歡迎關注微信公眾號:大禹程式設計,您的支援是對我最大的鼓勵!共同學習,共同進步: