免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
30分鐘迅速上手python

我從兩年前接觸python,到現(xiàn)在python已經(jīng)陪伴我渡過了我的大半個(gè)職業(yè)生涯,用過Django開發(fā)個(gè)人博客,用過pandas、numpy做過數(shù)據(jù)分析,還用過scikit-learn的數(shù)據(jù)挖掘算法,還使用過spider寫爬蟲,但是種種過往在腦中好似一場(chǎng)云煙,經(jīng)歷過卻什么都沒留下,所以從頭開始梳理,將Python的相關(guān)知識(shí)點(diǎn)一一記錄下來(lái)。
我一直使用的是經(jīng)典2.7,官方稱2020后將停止對(duì)2.x的維護(hù),但是我還是習(xí)慣使用2.7版本。另外可以使用from __future__ import module 這種形式在2.x中使用3.x的方法。

# 使用數(shù)字符號(hào)可以注釋單行.""" 強(qiáng)調(diào)內(nèi)容多行注釋可以使用三個(gè) """"

1. 原始數(shù)據(jù)類型和操作符

# 你的數(shù)字3  # => 3# 簡(jiǎn)單的數(shù)學(xué)計(jì)算1 + 1  # => 28 - 1  # => 710 * 2  # => 2035 / 5  # => 7# 除法相對(duì)來(lái)說(shuō)有點(diǎn)麻煩,因?yàn)槌ǖ慕Y(jié)果是整數(shù)還是浮點(diǎn)數(shù)是自動(dòng)的。5 / 2  # => 2# 為了解決除法,我們需要了解浮點(diǎn)數(shù).2.0  # 這就是一個(gè)浮點(diǎn)數(shù)11.0 / 4.0  # => 2.75 啊哈哈...是不是好多了# 整除的結(jié)果無(wú)論是正數(shù)還是負(fù)數(shù)都會(huì)截?cái)?5 // 3  # => 15.0 // 3.0  # => 1.0 # works on floats too-5 // 3  # => -2-5.0 // 3.0  # => -2.0# 注意我們可以通過導(dǎo)入模塊的方式使用一個(gè)/就進(jìn)行正常的除法.from __future__ import division11 / 4  # => 2.75  ...normal division11 // 4  # => 2 ...floored division# 模的操作7 % 3  # => 1# 求冪2 ** 4  # => 16# 使用括號(hào)強(qiáng)制定義優(yōu)先級(jí)(1 + 3) * 2  # => 8# 布爾操作# 注意 "and" 和"or" 是要區(qū)分大小寫的True and False  # => FalseFalse or True  # => True# 注意用整數(shù)進(jìn)行布爾操作0 and 2  # => 0-5 or 0  # => -50 == False  # => True2 == True  # => False1 == True  # => True# 用not來(lái)否定not True  # => Falsenot False  # => True# 等于是 ==1 == 1  # => True2 == 1  # => False# 不相等是 !=1 != 1  # => False2 != 1  # => True# 更多的比較1 < 10  # => True1 > 10  # => False2 <= 2  # => True2 >= 2  # => True# 可以進(jìn)行一串比較!1 < 2 < 3  # => True2 < 3 < 2  # => False# 可以使用 " 或 '來(lái)創(chuàng)造字符串"This is a string."'This is also a string.'# 字符串還可以進(jìn)行相加,代表拼接!"Hello " + "world!"  # => "Hello world!"# 沒有 '+' 也可以進(jìn)行拼接"Hello " "world!"  # => "Hello world!"# 增加更多"Hello" * 3  # => "HelloHelloHello"# 一個(gè)字符串可以被看做字符串列表"This is a string"[0]  # => 'T'# 可以獲取字符串的長(zhǎng)度len("This is a string")  # => 16# 使用 % 來(lái)對(duì)字符串進(jìn)行格式化,但是在3.1后面的版本將會(huì)被棄用.x = 'apple'y = 'lemon'z = "The items in the basket are %s and %s" % (x, y)# 還有一種新的方法是使用format方法對(duì)字符串進(jìn)行格式化,而且這也是首選的方法"{} 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 是一個(gè)對(duì)象None  # => None# 我們要使用"is"來(lái)比較一個(gè)對(duì)象是否為None,而不是"==" "etc" is None  # => FalseNone is None  # => True# 'is'可以測(cè)試對(duì)象的身份,但這個(gè)是對(duì)于對(duì)象來(lái)說(shuō)有用,對(duì)于原始的值來(lái)說(shuō)只能是然并卵# 任何一個(gè)對(duì)象都可以被用在一個(gè)布爾環(huán)境里面.# 下面這些值被認(rèn)為是錯(cuò)誤的:#    - None#    - zero of any numeric type (e.g., 0, 0L, 0.0, 0j)#    - empty sequences (e.g., '', (), [])#    - empty containers (e.g., {}, set())#    - instances of user-defined classes meeting certain conditions#      see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__## 其它的值被認(rèn)為是正確的 (使用 bool() 函數(shù)返回的將是 True).bool(0)  # => Falsebool("")  # => False

2. 變量和集合

# Python 又一個(gè)打印語(yǔ)句print "I'm Python. Nice to meet you!"  # => I'm Python. Nice to meet you!# 從控制臺(tái)上獲得輸入數(shù)據(jù)的簡(jiǎn)單方法input_string_var = raw_input("Enter some data: ")  # 得到的是一個(gè)字符串input_var = input("Enter some data: ")  # 將這個(gè)數(shù)據(jù)的值作為python代碼# 警告: 建議謹(jǐn)慎使用 input() 方法# 注意: 在 python 3, input() 被棄用,并且raw_input() 重命名為 input()# 在賦值變量前不需要聲明,這個(gè)不像C++那樣繁瑣.some_var = 5  # 慣例是使用小寫和下劃線some_var  # => 5# 使用一個(gè)之前沒有賦值的變量是一種異常.# 看報(bào)錯(cuò)內(nèi)容可以了解更多的異常信息.some_other_var  # 報(bào) name error# 使用一個(gè)表達(dá)式"yahoo!" if 3 > 2 else 2  # => "yahoo!"# 空列表li = []# 直接賦值列表other_li = [4, 5, 6]# 使用 append 方法為列表的末尾添加成員li.append(1)  # li 現(xiàn)在是 [1]li.append(2)  # li 現(xiàn)在是 [1, 2]li.append(4)  # li 現(xiàn)在是 [1, 2, 4]li.append(3)  # li 現(xiàn)在是 [1, 2, 4, 3]# 使用 pop 方法可以從列表的末尾刪除一個(gè)成員li.pop()  # => 3 and li 現(xiàn)在是 [1, 2, 4]# Let's put it backli.append(3)  # li 現(xiàn)在又是 [1, 2, 4, 3] .# 訪問列表就跟訪問數(shù)組一樣li[0]  # => 1# 分配新值給索引指向的值li[0] = 42li[0]  # => 42li[0] = 1  # 注意:把它設(shè)置成原來(lái)的值# 查看最后一個(gè)元素li[-1]  # => 3# 如果查詢的是一個(gè)超出索引的值就會(huì)報(bào)錯(cuò)li[4]  # Raises an IndexError# 你可以使用切片語(yǔ)法獲取一個(gè)范圍內(nèi)的值.# (開始和結(jié)束取決于你的數(shù)字位置.)li[1:3]  # => [2, 4]# 省略開始li[2:]  # => [4, 3]# 省略結(jié)束li[:3]  # => [1, 2, 4]# 每?jī)蓷l選擇一個(gè)li[::2]  # =>[1, 4]# 反轉(zhuǎn)整個(gè)列表li[::-1]  # => [3, 4, 2, 1]# 把他們結(jié)合起來(lái)做一個(gè)更先進(jìn)的切片# li[start:end:step]# 使用"del"刪除列表中的任意元素del li[2]  # li is now [1, 2, 3]# 通過列表相加的方式得到一個(gè)新列表li + other_li  # => [1, 2, 3, 4, 5, 6]# 注意: 原來(lái)的列表的值是沒有改變的.# 使用"extend()"方法對(duì)一個(gè)列表添加另一個(gè)列表li.extend(other_li)  # 現(xiàn)在li變成了 [1, 2, 3, 4, 5, 6]# 刪除第一個(gè)出現(xiàn)的值li.remove(2)  # li is now [1, 3, 4, 5, 6]li.remove(2)  # Raises a ValueError as 2 is not in the list# 在指定的索引出插入一個(gè)值li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again# 找到這個(gè)值對(duì)應(yīng)的索引li.index(2)  # => 1li.index(7)  # Raises a ValueError as 7 is not in the list# 使用 "in" 檢查元素是否在列表中1 in li  # => True# 使用 "len()" 查看列表的長(zhǎng)度len(li)  # => 6# 元組跟列表很像,但是不能改變.tup = (1, 2, 3)tup[0]  # => 1tup[0] = 3  # Raises a TypeError# 對(duì)于列表的很多操作,在元組中同樣也可以len(tup)  # => 3tup + (4, 5, 6)  # => (1, 2, 3, 4, 5, 6)tup[:2]  # => (1, 2)2 in tup  # => True# 你可以直接將元組或者列表直接賦值給變量a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3d, e, f = 4, 5, 6  # you can leave out the parentheses# 如果沒有括號(hào),將會(huì)默認(rèn)創(chuàng)建一個(gè)元組g = 4, 5, 6  # => (4, 5, 6)# 現(xiàn)在如果要交換兩個(gè)值將會(huì)變得非常簡(jiǎn)單e, d = d, e  # d is now 5 and e is now 4# 字典主要存儲(chǔ)映射empty_dict = {}# 直接賦值字典filled_dict = {"one": 1, "two": 2, "three": 3}# 使用 [] 查找字典里的值filled_dict["one"]  # => 1# 使用 "keys()" 可以得到所有的鍵值filled_dict.keys()  # => ["three", "two", "one"]# 注意- 字典的鍵是無(wú)須的,所以得到的值可能跟你一開始定義的不一樣# 使用 "values()" 可以得到所有的值filled_dict.values()  # => [3, 2, 1]# 注意- 同樣的值是無(wú)須的.# 使用"items()"可以得到一個(gè)以列表中的元組形式的“鍵值-值”對(duì)filled_dict.items()  # => [("one", 1), ("two", 2), ("three", 3)]# 使用 "in" 檢查元素鍵是否在字典中"one" in filled_dict  # => True1 in filled_dict  # => False# 查詢不存在的健是一個(gè) KeyErrorfilled_dict["four"]  # KeyError# 使用 "get()" 可以避免上面的錯(cuò)誤,如果沒有就會(huì)返回Nonefilled_dict.get("one")  # => 1filled_dict.get("four")  # => None# 通過設(shè)置默認(rèn)值的方式,可以顯示沒有鍵情況下的值filled_dict.get("one", 4)  # => 1filled_dict.get("four", 4)  # => 4# 注意這時(shí)候的 filled_dict.get("four") 還是 => None# (get 方法并不能添加字典里面的值)# 設(shè)置健值的方法跟列表的類似,直接賦值filled_dict["four"] = 4  # now, filled_dict["four"] => 4# 使用 "setdefault()" 方法,當(dāng)鍵不存在的時(shí)候就設(shè)置這個(gè)鍵和值,但是如果存在就不進(jìn)行改變filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5# 集合跟列表也很類似,但是不能包含重復(fù)值empty_set = set()# 使用 "set()" 對(duì)一群治進(jìn)行初始化some_set = set([1, 2, 2, 3, 4])  # some_set is now set([1, 2, 3, 4])# 雖然它看起來(lái)是經(jīng)過排序的,但是實(shí)際上它是無(wú)序的another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])# 從 2.7 開始, {} 可以用來(lái)聲明一個(gè)集合filled_set = {1, 2, 2, 3, 4}  # => {1, 2, 3, 4}# 向集合中添加更多的成員filled_set.add(5)  # filled_set is now {1, 2, 3, 4, 5}# 使用 & 對(duì)集合進(jìn)行交集操作other_set = {3, 4, 5, 6}filled_set & other_set  # => {3, 4, 5}# 使用 | 對(duì)集合進(jìn)行合集操作filled_set | other_set  # => {1, 2, 3, 4, 5, 6}# 使用 - 可以得到補(bǔ)集{1, 2, 3, 4} - {2, 3, 5}  # => {1, 4}# 使用 ^ 得到交集的補(bǔ)集{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  # => True10 in filled_set  # => False10 not in filled_set # => True# 查看變量的數(shù)據(jù)類型type(li)   # => listtype(filled_dict)   # => dicttype(5)   # => int

3. 控制流

# 先來(lái)一個(gè)變量some_var = 5# 這里又一個(gè)聲明,縮進(jìn)在python里非常重要!# 打印"some_var is smaller than 10"if some_var > 10:    print "some_var is totally bigger than 10."elif some_var < 10:  # 這個(gè) else 字句是可有可無(wú)的,根據(jù)需要.    print "some_var is smaller than 10."else:  # 這個(gè)也是.    print "some_var is indeed 10.""""For 循環(huán)在列表中遍歷prints:    dog is a mammal    cat is a mammal    mouse is a mammal"""for animal in ["dog", "cat", "mouse"]:    # 你可以使用 {0} 得到format里面的字符串. (See above.)    print "{0} is a mammal".format(animal)""""range(number)" 返回一個(gè)數(shù)字列表from 0 to 給出去的數(shù)字prints:    0    1    2    3"""for i in range(4):    print i""""range(lower, upper)" 返回一個(gè)數(shù)字列表from 小的數(shù)字 to 大的數(shù)字prints:    4    5    6    7"""for i in range(4, 8):    print i"""While 循環(huán)遇到條件就不在運(yùn)行.prints:    0    1    2    3"""x = 0while x < 4:    print x    x += 1  # 縮寫 x = x + 1# 處理異常使用 try/except 模塊try:    # 使用 "raise" 來(lái)提示錯(cuò)誤內(nèi)容    raise IndexError("This is an index error")except IndexError as e:    pass  # Pass 就是一個(gè)空操作,但是你要寫在這里.except (TypeError, NameError):    pass  # 如果需要,可以將多個(gè)異常處理掉.else:  # 可用可不用,根據(jù)需求,但是要在所有的except后面而且要符合邏輯    print "All good!"  # 只會(huì)在沒有報(bào)錯(cuò)的時(shí)候運(yùn)行finally:  # 在所有情況下都會(huì)執(zhí)行    print "We can clean up resources here"# 你可以使用下面這個(gè)字句代替 try/finally with open("myfile.txt") as f:    for line in f:        print line

4. 函數(shù)

# 使用 "def" 來(lái)創(chuàng)建一個(gè)函數(shù)def add(x, y):    print "x is {0} and y is {1}".format(x, y)    return x + y  # 使用 return 字句返回值# 使員工參數(shù)調(diào)用函數(shù)add(5, 6)  # => 打印 "x is 5 and y is 6" 并且返回值 11# 還可以使用關(guān)鍵字參數(shù)調(diào)用函數(shù)add(y=6, x=5)  # 關(guān)鍵字參數(shù)不需要在意排序.# 你可以使用 * 定義函數(shù)的位置變量參數(shù),使用的時(shí)候會(huì)被當(dāng)做一個(gè)元組def varargs(*args):    return argsvarargs(1, 2, 3)  # => (1, 2, 3)# 你還可以使用 ** 定義函數(shù)的關(guān)鍵字變量參數(shù),使用的時(shí)候會(huì)被當(dāng)做一個(gè)字典def keyword_args(**kwargs):    return kwargs# 調(diào)用之后看看會(huì)發(fā)生什么keyword_args(big="foot", loch="ness")  # => {"big": "foot", "loch": "ness"}# 只要你想要,兩個(gè)一起上也可以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}"""# 調(diào)用函數(shù)的時(shí)候,你也可以對(duì) args/kwargs 做相反的操作!# 先定義相關(guān)的args/kwargs,然后使用 * 傳遞位置參數(shù)、使員工 **傳遞關(guān)鍵字參數(shù).args = (1, 2, 3, 4)kwargs = {"a": 3, "b": 4}all_the_args(*args)  # 相當(dāng)于 all_the_args(1, 2, 3, 4)all_the_args(**kwargs)  # 相當(dāng)于 all_the_args(a=3, b=4)all_the_args(*args, **kwargs)  # 相當(dāng)于 all_the_args(1, 2, 3, 4, a=3, b=4)# 還可以分別使用 * and ** 來(lái)接受并傳遞其他函數(shù)的參數(shù)def pass_all_the_args(*args, **kwargs):    all_the_args(*args, **kwargs)    print varargs(*args)    print keyword_args(**kwargs)# 函數(shù)范圍x = 5def set_x(num):    # 局部變量 x 跟全局變量 x 不一樣    x = num  # => 43    print x  # => 43def set_global_x(num):    global x    print x  # => 5    x = num  # 全局變量 x 現(xiàn)在變成了 6    print x  # => 6set_x(43)set_global_x(6)# Python 有第一類型"""備注:根據(jù)變量的取值范圍、可操作性、可賦值性可以三種類型:一級(jí):可以作為參數(shù)傳遞也可以作為結(jié)果返回;二級(jí):可以作為參數(shù)傳遞,但是不能作為結(jié)果返回,也不能復(fù)制給變量;三級(jí):連作為參數(shù)傳遞也不行。"""def create_adder(x):    def adder(y):        return x + y    return adderadd_10 = create_adder(10)add_10(3)  # => 13# 還有一些匿名函數(shù)(lambda x: x > 2)(3)  # => True(lambda x, y: x ** 2 + y ** 2)(2, 1)  # => 5# 還有內(nèi)置的一些高階函數(shù)map(add_10, [1, 2, 3])  # => [11, 12, 13],map根據(jù)給定的函數(shù)對(duì)指定序列做映射map(max, [1, 2, 3], [4, 2, 1])  # => [4, 2, 3],提供兩個(gè)列表,對(duì)相同的位置進(jìn)行maxfilter(lambda x: x > 5, [3, 4, 5, 6, 7])  # => [6, 7]# 我們可以使用列表來(lái)更好的理解 maps 和 filters 函數(shù)[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]# 你也可以構(gòu)造字典或集合去理解.{x for x in 'abcddeef' if x in 'abc'}  # => {'a', 'b', 'c'}{x: x ** 2 for x in range(5)}  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

5. 類

# 我們從對(duì)象的子類中得到一個(gè)類.class Human(object):    # 類的屬性. 它會(huì)被這個(gè)類的所有實(shí)例共享    species = "H. sapiens"    # 當(dāng)類被實(shí)例化時(shí),稱為基本的初始化.    # 注意雙前下劃線和雙后下劃線表示python所使用的對(duì)象和或?qū)傩?,它們存在于用戶空盒子的名稱空間中,這些名字你最好別自己命名    def __init__(self, name):        # 分配參數(shù)給這個(gè)實(shí)例的 name 屬性        self.name = name        # 初始化屬性        self.age = 0    # 一個(gè)實(shí)例的方法. 所有的方法使用 "self" 作為第一個(gè)參數(shù)    def say(self, msg):        return "{0}: {1}".format(self.name, msg)    # 一個(gè)類方法是所有實(shí)例之間共享的    # 它們作為第一參數(shù),稱為調(diào)用類    @classmethod    def get_species(cls):        return cls.species    # 在沒有類和實(shí)例的情況下調(diào)用靜態(tài)方法    @staticmethod    def grunt():        return "*grunt*"    """    絲毫沒有g(shù)et到最后這三種方法的用處    """    # property 方法就像 getter 方法.    # 它將類方法轉(zhuǎn)化為一個(gè)相同名稱的只讀屬性.    @property    def age(self):        return self._age    # 允許去設(shè)置屬性    @age.setter    def age(self, age):        self._age = age    # 允許刪除屬性    @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"# 調(diào)用類方法i.get_species()  # => "H. sapiens"# 改變共有屬性Human.species = "H. neanderthalensis"i.get_species()  # => "H. neanderthalensis"j.get_species()  # => "H. neanderthalensis"# 調(diào)用靜態(tài)方法Human.grunt()  # => "*grunt*"# 更新屬性i.age = 42# 得到屬性i.age  # => 42# 刪除屬性del i.agei.age  # => raises an AttributeError##################################################### 6. 模塊##################################################### 引入模塊import mathprint math.sqrt(16)  # => 4# 從模塊中引入指定函數(shù)from math import ceil, floorprint ceil(3.7)  # => 4.0print floor(3.7)  # => 3.0# 從模塊中引入所有的函數(shù).# Warning: 不推薦這么做from math import *# 還可以對(duì)模塊重命名import math as mmath.sqrt(16) == m.sqrt(16)  # => True# y你可以測(cè)試下這些其實(shí)等價(jià)的from math import sqrtmath.sqrt == m.sqrt == sqrt  # => True# Python的模塊值是普通的文件.你可以自己寫個(gè),然后引入. 模塊的名稱就是文件的名稱.# 你可以找出是哪些函數(shù)和屬性定義了一個(gè)模塊import mathdir(math)# 如果在現(xiàn)有模塊的文件夾中有一個(gè)腳本名稱為 math.py ,這個(gè)腳本將會(huì)代替Python的自建模塊,這是因?yàn)楸镜氐奈募?yōu)先級(jí)高于自建的庫(kù)

7. 高級(jí)(暫未涉及)

# 生成器# A generator "generates" values as they are requested instead of storing everything up front# The following method (*NOT* a generator) will double all values and store it in `double_arr`. For large size of iterables, that might get huge!def double_numbers(iterable):    double_arr = []    for i in iterable:        double_arr.append(i + i)    return double_arr# Running the following would mean we'll double all values first and return all of them back to be checked by our conditionfor value in double_numbers(range(1000000)):  # `test_non_generator`    print value    if value > 5:        break# We could instead use a generator to "generate" the doubled value as the item is being requesteddef double_numbers_generator(iterable):    for i in iterable:        yield i + i# Running the same code as before, but with a generator, now allows us to iterate over the values and doubling them one by one as they are being consumed by our logic. Hence as soon as we see a value > 5, we break out of the loop and don't need to double most of the values sent in (MUCH FASTER!)for value in double_numbers_generator(xrange(1000000)):  # `test_generator`    print value    if value > 5:        break# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`?# Just as `double_numbers_generator` is the generator version of `double_numbers`# We have `xrange` as the generator version of `range`# `range` would return back and array with 1000000 values for us to use# `xrange` would generate 1000000 values for us as we request / iterate over those items# Just as you can create a list comprehension, you can create generator comprehensions as well.values = (-x for x in [1, 2, 3, 4, 5])for x in values:    print(x)  # prints -1 -2 -3 -4 -5 to console/terminal# You can also cast a generator comprehension directly to a list.values = (-x for x in [1, 2, 3, 4, 5])gen_to_list = list(values)print(gen_to_list)  # => [-1, -2, -3, -4, -5]# 裝飾器# A decorator is a higher order function, which accepts and returns a function.# Simple usage example – add_apples decorator will add 'Apple' element into fruits list returned by get_fruits target function.def add_apples(func):    def get_fruits():        fruits = func()        fruits.append('Apple')        return fruits    return get_fruits@add_applesdef get_fruits():    return ['Banana', 'Mango', 'Orange']# Prints out the list of fruits with 'Apple' element in it: Banana, Mango, Orange, Appleprint ', '.join(get_fruits())# in this example beg wraps say# Beg will call say. If say_please is True then it will change the returned messagefrom functools import wrapsdef 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@begdef say(say_please=False):    msg = "Can you buy me a beer?"    return msg, say_pleaseprint say()  # Can you buy me a beer?print say(say_please=True)  # Can you buy me a beer? Please! I am poor :(
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
X分鐘速成Y=python 快速入門
10 分鐘速成 Python3
十五分鐘讓你了解Python套路
萬(wàn)字干貨,Python語(yǔ)法大合集,一篇文章帶你入門
Python入門很難?別擔(dān)心,找對(duì)方法!函數(shù)基礎(chǔ)知識(shí)送給你們
Python函數(shù)詳解
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服