python 2x可以打么_15分钟让你了解Python套路,看你能不能坚持的住
古人云:書山有路勤為徑 學(xué)海無(wú)涯苦作舟 。
注:一般標(biāo)榜著 “ XX天學(xué)會(huì)XX”、“ XX 分鐘了解XX”的文章都不會(huì)是讓你增長(zhǎng)功力的文章,如本文。
隨著互聯(lián)網(wǎng)發(fā)展,全球在快速數(shù)字化,編程這件事也從數(shù)十年前只有科研人員在實(shí)驗(yàn)室才能做的事變得越來(lái)越讓人們所熟悉。但是作為平時(shí)甚少接觸編程的小伙伴,是不是也會(huì)對(duì)計(jì)算機(jī)世界擁有一點(diǎn)點(diǎn)好奇心呢(比如電影《黑客帝國(guó)》、《源代碼》)?
Q1: "怎么進(jìn)入編程世界?"首先,你要學(xué)會(huì)一門編程語(yǔ)言!
而我要推薦的計(jì)算機(jī)語(yǔ)言,答案已在標(biāo)題中被出賣:Python!
Python是一門十分容易上手,但是又被IT業(yè)界廣泛使用的編程語(yǔ)言(Scratch這種圖形化編程雖然簡(jiǎn)單,但基本只能用于教學(xué))。2016年5月份Python在全球最受歡迎編程語(yǔ)言中排第五。
Q2: “Python如何學(xué)?”如果你是一位從未接觸過(guò)編程語(yǔ)言的新手,請(qǐng)移步 這里。 此書作者是一位程序員大叔,大叔說(shuō)了:“學(xué)編程,首先,得會(huì)打字!!不會(huì)打字您就別學(xué)了哈”。大叔的在書提出的觀點(diǎn)個(gè)人覺(jué)得也是值得學(xué)習(xí)的,無(wú)論用于編程還是其他事情,如: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.”萬(wàn)事開(kāi)頭難,但自己選擇的路,即使跪著也要走完。也許你是那種一碰到困難就想到放棄的人;也許你從未掌握“自律”這件事導(dǎo)致你無(wú)法做任何“枯燥”的事情;也許你一直被認(rèn)為是“天才”,所以你不會(huì)傻到嘗試去做那些有可能讓你看起來(lái)是一個(gè)笨蛋或者至少不是“神童”的事情;也許你覺(jué)得和我這種已經(jīng)編程超過(guò)20年的人比較編程這件事是一件逗逼的事情。無(wú)論是什么原因使你想要退出,不要管它!要管住自己(譯者注:論“自虐”能力的重要性。)! 如果某一個(gè)練習(xí)你不會(huì)做,或者有一課你聽(tīng)不明白,那就跳過(guò)它,然后再回來(lái)重新學(xué)習(xí)(譯者注:子曰:溫故而知新)。編程這事說(shuō)起來(lái)是件奇怪的事情,當(dāng)你沒(méi)有領(lǐng)悟真諦的時(shí)候你只需要堅(jiān)持。像學(xué)習(xí)任何一門自然語(yǔ)言一樣,剛開(kāi)始時(shí)可能總會(huì)感覺(jué)怪怪的。那些奇怪的單詞,那些你不知道的符號(hào),也許會(huì)讓你感到十分困惑。但只要你堅(jiān)持不懈,堅(jiān)持做本書中的那些練習(xí)并且嘗試著去理解它們。會(huì)有一天,你的腦子會(huì)突然閃出“哇哈~!原來(lái)是這樣!” 的頓悟時(shí)刻。也許你不會(huì)成為一個(gè)高級(jí)碼農(nóng),但是至少你將會(huì)知道編程到底是什么鬼。
言歸正傳,本文面向?qū)ο鬄榫哂幸欢↑c(diǎn)編程經(jīng)驗(yàn)的小伙伴,旨在快速了解Python的基本語(yǔ)法和部分特性。
前言
# Python中單行注釋請(qǐng)用‘#’
""" Python中多行注釋
請(qǐng)用""",我寫不了那么
多字,隨便湊個(gè)樣板。
"""
1. 基本類型和運(yùn)算符
# 定義了一個(gè)數(shù)字 3
3 ?# => 3
# 基本計(jì)算
1 + 1 ?# => 2
8 - 1 ?# => 7
10 * 2 ?# => 20
35 / 5 ?# => 7
# 當(dāng)除數(shù)和被除數(shù)都為整型時(shí),除 這個(gè)操作只求整數(shù)
# ( python2.x語(yǔ)法。經(jīng)測(cè)試,Python3.x 已經(jīng)全部當(dāng)做浮點(diǎn)數(shù)處理,還會(huì)計(jì)算小數(shù))
5 / 2 ?# => 2
10/-3 #python3的結(jié)果為-3.3333333333333335 python2 結(jié)果為-4
10/3 #python3的結(jié)果為3.3333333333333335 python2 結(jié)果為3
#由上面兩個(gè)結(jié)果也可以看出,在Python2中,如結(jié)果有小數(shù),則會(huì)取最近最小整數(shù)
# 如果我們除數(shù)和被除數(shù)為浮點(diǎn)型,則Python會(huì)自動(dòng)把結(jié)果保存為浮點(diǎn)數(shù)
2.0 ?# 這是浮點(diǎn)數(shù)
11.0 / 4.0 ?# 這個(gè)時(shí)候結(jié)果就是2.75啦!是不是很神奇?
# 當(dāng)用‘//’進(jìn)行計(jì)算時(shí),python3不會(huì)全部單做浮點(diǎn)數(shù)處理.
5 // 3 ? # => 1
5.0 // 3.0 # => 1.0
-5 // 3 ?# => -2
-5.0 // 3.0 # => -2.0
from __future__ import division # 注可以在通過(guò) __future__ ?關(guān)鍵字
# 在python2中引入python3 特性
11/4 ? ?# => 2.75 ?... 標(biāo)準(zhǔn)除法
11//4 ? # => 2 ... 除后取整
# 求余數(shù)操作
7 % 3 # => 1
# 冪操作 2的4次方
2**4 # => 16
# 先乘除,后加減,口號(hào)優(yōu)先
(1 + 3) * 2 ?# => 8
# 布爾值操作
# 注:or 和 and 兩個(gè)關(guān)鍵字是大小寫敏感的
True and False #=> 返回False
False or True #=> 返回True
# 布爾值和整形的關(guān)系,除了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
# 非等比較“!=”,如果兩個(gè)數(shù)不相等返回True,相等返回Flase
1 != 1 ?# => False
2 != 1 ?# => True
# 大于/小于 和等于的組合比較
1 < 10 ?# => True
1 > 10 ?# => False
2 <= 2 ?# => True
2 >= 2 ?# => True
# Python可以支持多數(shù)值進(jìn)行組合比較,
#但只要一個(gè)等值為False,則結(jié)果為False
1 < 2 < 3 ?# => True
2 < 3 < 2 ?# => False
# 可以通過(guò) " 或者 '來(lái)創(chuàng)建字符串
"This is a string."
'This is also a string.'
# 字符串間可以通過(guò) + 號(hào)進(jìn)行相加,是不是簡(jiǎn)單到爆?
"Hello " + "world!" ?# => "Hello world!"
# 甚至不使用'+'號(hào),也可以把字符串進(jìn)行連接
"Hello " "world!" ?# => "Hello world!"
#可以通過(guò) * 號(hào),對(duì)字符串進(jìn)行復(fù)制,比如 ;
importantNote = "重要的事情說(shuō)三遍\n" * 3
print (importantNote)
""" 結(jié)果為:
重要的事情說(shuō)三遍
重要的事情說(shuō)三遍
重要的事情說(shuō)三遍
"""
"Hello" * 3 ?# => "HelloHelloHello"
# 字符串可以在任意位置被打斷
"This is a string"[0] ?# => 'T'
#字符串可以用 %連接,并且可以打印出變量值
#(和C/C++ 一樣%d 表示整數(shù),%s表示字符串,
#但python可以自己進(jìn)行判斷,我們無(wú)需太擔(dān)心這個(gè)問(wèn)題)
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x,y)
# 一個(gè)新的更好的字符串連接方式是通過(guò).format()函數(shù),推薦使用該方式
"{} 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,它是一個(gè)特殊的變量
None ?# => None
# 在和None進(jìn)行比較時(shí),不要用“==”操作符,用 “is”
"etc" is None ?# => False
None is None ?# => True
#“is"操作符用于對(duì)象之間的比較,
#對(duì)于底層類型進(jìn)行比較時(shí)
#不建議用“is”,但對(duì)于對(duì)象之間的比較,用“is”是最合適的
# bool可以用于對(duì)任何對(duì)象進(jìn)行判斷
# 以下這些值是非真的
# ? - None
# ? - 各類數(shù)值型的0 (e.g., 0, 0L, 0.0, 0j)
# ? - 空元組、空列表 (e.g., '', (), [])
# ? - 空字典、空集合 (e.g., {}, set())
# ? - 其他值請(qǐng)參考:
# ? ? 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!
# 從控制臺(tái)中獲取輸入
input_string_var = raw_input("Enter some data: ") # 返回字符串類型
input_var = input("Enter some data: ") # python會(huì)判斷類型如果是字符串 則輸入時(shí)要加“”or''
# 注意:在 python 3中, input() 由 raw_input() 代替
# 在Python中不需要設(shè)定變量類型,python會(huì)自動(dòng)根據(jù)值進(jìn)行判斷
some_var = 5
some_var ?# => 5
# if 可以作為表達(dá)時(shí)被使用,下句可以這樣理解 “輸出‘yahool’如果3大于2的話,不然輸出2“
"yahoo!" if 3 > 2 else 2 ?# => "yahoo!"
列表
# python中的列表定義
li = []
# 也可以通過(guò)初始化時(shí)內(nèi)置列表的值
other_li = [4, 5, 6]
# append函數(shù)可以在列表中插入值
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函數(shù)從列表末移除值
li.pop() ? ? ? ?# => 3 and li is now [1, 2, 4]
# 移除后通過(guò)append接回
li.append(3) ? ?# li is now [1, 2, 4, 3] again.
# 通過(guò)[]的方式可以提取任何列表中的任意值
#(前提,index不大于列表總數(shù))
li[0] ?# => 1
# 也可以通過(guò)[]下標(biāo)的方式直接給列表賦值
li[0] = 42
li[0] ?# => 42
# 如果[]小標(biāo)的值為負(fù)數(shù),則表示以逆序獲取列表中的值
li[-1] ?# => 3
# 查詢的值不可以超出列表個(gè)數(shù),否則報(bào)錯(cuò)。
# 但是利用insert()插入時(shí)可以,超出范圍的值會(huì)直接被插入到列表最末
li[4] ?# Raises an IndexError
# 可以通過(guò)[:],獲取列表中指定范圍的值
# (It's a closed/open range for you mathy types.)
# 這是半開(kāi)取值法,比如li[1:3],取的是列表中index為1、2的兩個(gè)值,
# 該法則適用于以下所有通過(guò)[]取值的方式
li[1:3] ?# => [2, 4]
# 如果一邊不去值,則表示取所有該邊的值。
li[2:] ?# => [4, 3]
li[:3] ?# => [1, 2, 4]
# [::2]表示選擇從[0]開(kāi)始,步長(zhǎng)為2上的值
li[::2] ? # =>[1, 4]
# [::-1]表示反向選擇,-可以理解為 反向選擇,而1表示步長(zhǎng),步長(zhǎng)1則包含了列表中的所有元素
li[::-1] ? # => [3, 4, 2, 1]
# []規(guī)則完整版表示方法[開(kāi)始:結(jié)束:步長(zhǎng)]
# li[start:end:step]
# ?"del"關(guān)鍵字可以直接刪除列表中的值
del li[2] ? # li is now [1, 2, 3]
# 可以通過(guò)“+”操作符對(duì)列表進(jìn)行操作,注:列表只有 + 操作,而集合(set)有+ 和 -
li + other_li ? # => [1, 2, 3, 4, 5, 6]
# 也可以 "extend()"方法對(duì)列表進(jìn)行擴(kuò)展
li.extend(other_li) ? # Now li is [1, 2, 3, 4, 5, 6]
# Remove 方法和 del 類似,但remove的直接是數(shù)值,而不是index
li.remove(2) ?# li is now [1, 3, 4, 5, 6]
li.remove(2) ?# 如果remove的值不存在列表中,則會(huì)報(bào)錯(cuò)
# 在指定位置插入數(shù)值,上面已經(jīng)提過(guò),如果index值超過(guò)的話,會(huì)直接插到列表末
li.insert(1, 2) ?# li is now [1, 2, 3, 4, 5, 6] again
# 獲取某個(gè)值的index
li.index(2) ?# => 1
li.index(7) ?# 如果
# "in"可以直接查看某個(gè)值是否存在于列表中
1 in li ? # => True
# "len()"函數(shù)可以檢測(cè)隊(duì)列的數(shù)量
len(li) ? # => 6
元組
# Tuples(元組)是一個(gè)類似數(shù)列的數(shù)據(jù)結(jié)構(gòu),但是元組是不可修改的
tup = (1, 2, 3)
tup[0] ? # => 1
tup[0] = 3 ?# 一修改就會(huì)報(bào)錯(cuò)
#數(shù)列中的方法在元組也可以使用(除了 修改)
len(tup) ? # => 3
tup + (4, 5, 6) ? # => (1, 2, 3, 4, 5, 6)
tup[:2] ? # => (1, 2)
2 in tup ? # => True
# 可以一次性賦值幾個(gè)變量
a, b, c = (1, 2, 3) ?# a 為1,b為2,c為3
d, e, f = 4, 5, 6 ? ? ?# 元組賦值也可以不用括號(hào)
# 同樣元組不用括號(hào)也同樣可以創(chuàng)建
g = 4, 5, 6 ? ? ? ? ?# => (4, 5, 6)
# Python中的數(shù)據(jù)交換十分簡(jiǎn)單:只要在賦值時(shí)互調(diào)位置即可
e, d = d, e ?# d is now 5 and e is now 4
字典
# Python中的字典定義
empty_dict = {}
# 也可以通過(guò)定義時(shí)賦值給字典
filled_dict = {"one": 1, "two": 2, "three": 3}
# 可以通過(guò)[]的key方式查詢字典中的值
filled_dict["one"] ? # => 1
# 可以通過(guò)"keys()"方法獲取字典中的所有key值
filled_dict.keys() ? # => ["three", "two", "one"]
# Note - 返回的keys并不一定按照順序排列的.
# 所以測(cè)試結(jié)果可能和上述結(jié)果不一致
# 通過(guò) "values()"的方式可以獲取字典中所有值,
#同樣他們返回的結(jié)果也不一定按照順序排列
filled_dict.values() ? # => [3, 2, 1]
# 可以通過(guò) "in"方式獲取查詢某個(gè)鍵值是否存在字典中,但是數(shù)值不可以
"one" in filled_dict ? # => True
1 in filled_dict ? # => False
# 查找不存在的key值時(shí),Python會(huì)報(bào)錯(cuò)
filled_dict["four"] ? # KeyError
#用 "get()" 方法可以避免鍵值錯(cuò)誤的產(chǎn)生
filled_dict.get("one") ? # => 1
filled_dict.get("four") ? # => None
# 當(dāng)鍵值不存在的時(shí)候,get方法可以通過(guò)返回默認(rèn)值,
# 但是并沒(méi)有對(duì)值字典進(jìn)行賦值
filled_dict.get("one", 4) ? # => 1
filled_dict.get("four", 4) ? # => 4
# 字典中設(shè)置值的方式和列表類似,通過(guò)[]方式可以設(shè)置
filled_dict["four"] = 4 ?# now, filled_dict["four"] => 4
# "setdefault()" 可以設(shè)置字典中的值
# 但是注意:只有當(dāng)該鍵值之前未存在的時(shí)候,setdefault()函數(shù)才生效
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的方式可以通過(guò) set()來(lái)實(shí)現(xiàn)
some_set = set([1, 2, 2, 3, 4]) ? # some_set is now set([1, 2, 3, 4])
# 集合的排列是無(wú)序的!集合的排列是無(wú)序的!集合的排列是無(wú)序的!
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}
#集合可通過(guò) &操作符取交集
other_set = {3, 4, 5, 6}
filled_set & other_set ? # => {3, 4, 5}
# 通過(guò)|操作符取并集
filled_set | other_set ? # => {1, 2, 3, 4, 5, 6}
# 通過(guò) - 操作符取差集
{1, 2, 3, 4} - {2, 3, 5} ? # => {1, 4}
# 通過(guò) ^ 操作符取非集
{1, 2, 3, 4} ^ {2, 3, 5} ?# => {1, 4, 5}
# 通過(guò) >= 判斷左邊集合是否是右邊集合的超集
{1, 2} >= {1, 2, 3} # => False
# 通過(guò) <= 判斷左邊集合是否右邊集合的子集
{1, 2} <= {1, 2, 3} # => True
# 通過(guò) in 可以判斷元素是否在集合中
2 in filled_set ? # => True
10 in filled_set ? # => FalsePython數(shù)據(jù)集合類型總結(jié)列表 定義方式 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 邏輯運(yùn)算符
# 創(chuàng)建一個(gè)變量
some_var = 5
# 通過(guò)if進(jìn)行邏輯判斷
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."
"""
通過(guò)for...in...進(jìn)行循環(huán)打印:
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)
"""
通過(guò)"range()" 方式,控制for的循環(huán)次數(shù)
prints:
0
1
2
3
"""
for i in range(4):
print i
"""
"range(lower, upper)" 返回 lower 到 upper的值,
注意:range左邊必須小于右邊參數(shù)
prints:
4
5
6
7
"""
for i in range(4, 8):
print i
"""
while 循環(huán)
prints:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 ?# Shorthand for x = x + 1
# Python支持 try/except 語(yǔ)法
# Python2.6以上的版本,支持try...except...:
try:
# raise顯示地引發(fā)異常。一旦執(zhí)行了raise語(yǔ)句,raise后面的語(yǔ)句將不能執(zhí)行。
raise IndexError("This is an index error")
except IndexError as e:
pass ? ?# pass 空語(yǔ)句,跳過(guò)處理
except (TypeError, NameError):
pass ? ?# python 支持同時(shí)檢測(cè)多個(gè)錯(cuò)誤
else: ? # Python必須要處理所有情況,這里是其他未定義的情況
print "All good!"
finally: # ?finally無(wú)論有沒(méi)有異常都會(huì)執(zhí)行
print "We can clean up resources here"
#通過(guò)with函數(shù),可以替代try....except...函數(shù) ?[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 關(guān)鍵字定義函數(shù)
def add(x, y):
print "x is {0} and y is {1}".format(x, y)
return x + y ? ?#可以直接return結(jié)果
# 函數(shù)調(diào)用參數(shù)
add(5, 6) ? # => prints out "x is 5 and y is 6" and returns 11
# Python支持參數(shù)互換,只需要在調(diào)用函數(shù)時(shí)加上形參
add(y=6, x=5) ? # Keyword arguments can arrive in any order.
# Python函數(shù)支持可變參數(shù)
# ?在定義函數(shù)時(shí)通過(guò)*號(hào)表示可變長(zhǎng)參數(shù)
def varargs(*args):
return args
varargs(1, 2, 3) ? # => (1, 2, 3)
# 可以通過(guò)**的方式定義Key可變長(zhǎng)參數(shù)查找字典中的關(guān)鍵詞
def keyword_args(**kwargs):
return kwargs
# 當(dāng)函數(shù)參數(shù)是**類型的時(shí)候,Python可以通過(guò)該函數(shù)定義字典
keyword_args(big="foot", loch="ness") ? # => {"big": "foot", "loch": "ness"}
#同時(shí)支持函數(shù)和字典類型參數(shù),具體事例如下:
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í),可以同時(shí)賦值,文字難以表達(dá),例子如下:
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)
# 在函數(shù)中也可以通過(guò)單獨(dú)處理* 或者 **的方式,增加函數(shù)的健壯性
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):
# 當(dāng)在函數(shù)里面改變變量時(shí),如果沒(méi)有加gloabl關(guān)鍵字,則改變的是局部變量
x = num # => 43
print x # => 43
def set_global_x(num):
global x
print x # => 5
x = num # 加了global關(guān)鍵字后,即可在函數(shù)內(nèi)操作全局變量
print x # => 6
set_x(43)
set_global_x(6)
# 返回函數(shù)指針?lè)绞蕉x函數(shù)/*換個(gè)說(shuō)法,匿名函數(shù)*/
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) ? # => 13
# Lambda 關(guān)鍵字定義的匿名函數(shù)
(lambda x: x > 2)(3) ? # => True
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
# map方式也可以調(diào)用函數(shù)并傳入?yún)?shù)
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]
# 可以通過(guò)這兩種方式結(jié)合調(diào)用,下面的函數(shù)解析:
#add_10(i) 是映射了for...in...函數(shù)的返回值,返回值作為參數(shù)傳進(jìn)。
[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中的類
# 下面代碼是定義了一個(gè)Human類,繼承自object類
# Python類可以繼承自多個(gè)類,如class Human(object,orangOutang)
class Human(object):
# 類變量
species = "H. sapiens"類接口
__species = "Other.sapiens" #內(nèi)部結(jié)構(gòu),無(wú)法被外部直接訪問(wèn)
# __init__(),初始化函數(shù),python中在對(duì)類進(jìn)行處理時(shí),會(huì)先處理以下函數(shù),
#其實(shí)就是系統(tǒng)默認(rèn)定義了接口,而這個(gè)接口是開(kāi)放給用戶去實(shí)現(xiàn)的,具體如下:
#__init__ ?構(gòu)造函數(shù),在生成對(duì)象時(shí)調(diào)用
# __del__ ? 析構(gòu)函數(shù),釋放對(duì)象時(shí)使用
#__repr__ 打印,轉(zhuǎn)換
#__setitem__按照索引賦值
#__getitem__按照索引獲取值
#__len__獲得長(zhǎng)度
#__cmp__比較運(yùn)算
#__call__函數(shù)調(diào)用
#__add__加運(yùn)算
#__sub__減運(yùn)算
#__mul__乘運(yùn)算
#__div__除運(yùn)算
#__mod__求余運(yùn)算
#__pow__稱方
def __init__(self, name):
#聲明類中的屬性,并初始化,在初始化的時(shí)候同時(shí)
#就是定義了變量類型
self.name = name
self.age = 0
# 在類中所有函數(shù)都必須把self作為第一個(gè)參數(shù)
#(下面定義的類方法和靜態(tài)方法除外)
def say(self, msg):
return "{0}: {1}".format(self.name, msg)
# 類方法
@classmethod
def get_species(cls):
return cls.species
# 靜態(tài)方法,
@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屬性,相當(dāng)于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
#類實(shí)例化
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)用實(shí)例方法用"."
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*"
# 給age賦值
i.age = 42
# 獲取age值
i.age # => 42
# 刪除age
del i.age
i.age ?# => raises an AttributeError
6. Python的模塊(庫(kù))
# Python中的一個(gè)*.py文件就是一個(gè)模塊
import math
print math.sqrt(16) ?# => 4
# 可以只引入模塊中的某些類/方法
from math import ceil, floor
print ceil(3.7) ?# => 4.0
print floor(3.7) ? # => 3.0
# 也可以通過(guò)*引入全部方法
# Warning: this is not recommended
from math import *
#math庫(kù)的縮寫可以為m
math.sqrt(16) == m.sqrt(16) ? # => True
# 可以直接引入sqrt庫(kù)
from math import sqrt
math.sqrt == m.sqrt == sqrt ?# => True
#python的庫(kù)就只是文件
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.
#如果你在當(dāng)前目錄下有一個(gè)Python腳本的名字也叫math.py
#當(dāng)前目錄下的math.py會(huì)替換掉內(nèi)置的Python模塊
#因?yàn)樵赑ython中當(dāng)前目錄的優(yōu)先級(jí)會(huì)高于內(nèi)置模塊的優(yōu)先級(jí)
7. Python中的高級(jí)特性(生成器、裝飾器:wraps)
# Generators ,生成器函數(shù)在Python中與迭代器協(xié)議的概念聯(lián)系在一起。
# 簡(jiǎn)而言之,包含yield語(yǔ)句的函數(shù)會(huì)被特地編譯成生成器。
# 當(dāng)函數(shù)被調(diào)用時(shí),他們返回一個(gè)生成器對(duì)象,這個(gè)對(duì)象支持迭代器接口。函數(shù)
#也許會(huì)有個(gè)return語(yǔ)句,但它的作用是用來(lái)yield產(chǎn)生值的。
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 :
喜歡的記得三連,或者補(bǔ)充哦~
有需要python干糧的小伙伴,可以私信阿婆主
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的python 2x可以打么_15分钟让你了解Python套路,看你能不能坚持的住的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: synchronized原理_synch
- 下一篇: python僵尸进程和孤儿进程_pyth