十五分鐘讓你了解Python套路

Mr.C/文

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

注:一般標榜著 “ 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 = "重要的事情說三遍\n" * 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 :

[1]learnxinyminutes,本文代碼大部分取于該網站,在此對該網站作者表示感謝!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,247評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,520評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,362評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,805評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,541評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,896評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,887評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,062評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,608評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,356評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,555評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,077評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,769評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,175評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,489評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,289評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,516評論 2 379

推薦閱讀更多精彩內容