博客 / 詳情

返回

Y 分鐘速成 Python

源代碼下載: learnpython-cn.py

Python 是由吉多·範羅蘇姆(Guido Van Rossum)在 90 年代早期設計。
它是如今最常用的編程語言之一。它的語法簡潔且優美,幾乎就是可執行的偽代碼。

歡迎大家斧正。英文版原作 Louie Dinh @louiedinh
郵箱 louiedinh [at] [谷歌的信箱服務]。中文翻譯 Geoff Liu。

注意:這篇教程是基於 Python 3 寫的。如果你想學舊版 Python 2,我們特別有另一篇教程。

# 用井字符開頭的是單行註釋

""" 多行字符串用三個引號
    包裹,也常被用來做多
    行註釋
"""

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

# 整數
3  # => 3

# 算術沒有什麼出乎意料的
1 + 1   # => 2
8 - 1   # => 7
10 * 2  # => 20

# 但是除法例外,會自動轉換成浮點數
35 / 5  # => 7.0
10.0 / 3  # => 3.3333333333333335

# 整數除法的結果都是向下取整
5 // 3       # => 1
5.0 // 3.0   # => 1.0 # 浮點數也可以
-5 // 3      # => -2
-5.0 // 3.0  # => -2.0

# 浮點數的運算結果也是浮點數
3 * 2.0 # => 6.0

# 模除
7 % 3 # => 1
# i % j 結果的正負符號會和 j 相同,而不是和 i 相同
-7 % 3 # => 2

# x 的 y 次方
2**4 # => 16

# 用括號決定優先級
1 + 3 * 2    # => 7
(1 + 3) * 2  # => 8

# 布爾值 (注意: 首字母大寫)
True   # => True
False  # => False

# 用 not 取非
not True   # => False
not False  # => True

# 邏輯運算符,注意 and 和 or 都是小寫
True and False # => False
False or True # => True

# True 和 False 實質上就是數字 1 和0
True + True # => 2
True * 8    # => 8
False - 5   # => -5

# 數值與 True 和 False 之間的比較運算
0 == False # => True
2 == True # => False
1 == True # => True
-5 != False # => True

# 使用布爾邏輯運算符對數字類型的值進行運算時,會把數值強制轉換為布爾值進行運算
# 但計算結果會返回它們的強制轉換前的值
# 注意不要把 bool(ints) 與位運算的 "按位與"、"按位或" (&, |) 混淆
bool(0)     # => False
bool(4)     # => True
bool(-6)    # => True
0 and 2     # => 0
-5 or 0     # => -5

# 用==判斷相等
1 == 1  # => True
2 == 1  # => False

# 用!=判斷不等
1 != 1  # => False
2 != 1  # => True

# 比較大小
1 < 10  # => True
1 > 10  # => False
2 <= 2  # => True
2 >= 2  # => True

# 判斷一個值是否在範圍裏
1 < 2 and 2 < 3  # => True
2 < 3 and 3 < 2  # => False
# 大小比較可以連起來!
1 < 2 < 3  # => True
2 < 3 < 2  # => False

# (is 對比 ==) is 判斷兩個變量是否引用同一個對象,
# 而 == 判斷兩個對象是否含有相同的值
a = [1, 2, 3, 4]  # 變量 a 是一個新的列表, [1, 2, 3, 4]
b = a             # 變量 b 賦值了變量 a 的值
b is a            # => True, a 和 b 引用的是同一個對象
b == a            # => True, a 和 b 的對象的值相同
b = [1, 2, 3, 4]  # 變量 b 賦值了一個新的列表, [1, 2, 3, 4]
b is a            # => False, a 和 b 引用的不是同一個對象
b == a            # => True, a 和 b 的對象的值相同


# 創建字符串可以使用單引號(')或者雙引號(")
"這是個字符串"
'這也是個字符串'

# 字符串可以使用加號連接成新的字符串
"Hello " + "world!"  # => "Hello world!"
# 非變量形式的字符串甚至可以在沒有加號的情況下連接
"Hello " "world!"    # => "Hello world!"

# 字符串可以被當作字符列表
"Hello world!"[0]  # => 'H'

# 你可以獲得字符串的長度
len("This is a string")  # => 16

# 你可以使用 f-strings 格式化字符串(python3.6+)
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
# 你可以在大括號內幾乎加入任何 python 表達式,表達式的結果會以字符串的形式返回
f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."

# 用 .format 來格式化字符串
"{} can be {}".format("strings", "interpolated")
# 可以重複參數以節省時間
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# => "Jack be nimble, Jack be quick, Jack jump over the candle stick"
# 如果不想數參數,可以用關鍵字
"{name} wants to eat {food}".format(name="Bob", food="lasagna") 
# => "Bob wants to eat lasagna"

# 如果你的 Python3 程序也要在 Python2.5 以下環境運行,也可以用老式的格式化語法
"%s can be %s the %s way" % ("strings", "interpolated", "old")

# None是一個對象
None  # => None

# 當與 None 進行比較時不要用 ==,要用 is。is 是用來比較兩個變量是否指向同一個對象。
"etc" is None  # => False
None is None  # => True

# None,0,空字符串,空列表,空字典,空元組都算是 False
# 所有其他值都是 True
bool(0)  # => False
bool("")  # => False
bool([]) # => False
bool({}) # => False
bool(()) # => False


####################################################
## 2. 變量和集合
####################################################

# print是內置的打印函數
print("I'm Python. Nice to meet you!")

# 默認情況下,print 函數會在輸出結果後加入一個空行作為結尾
# 可以使用附加參數改變輸出結尾
print("Hello, World", end="!")  # => Hello, World!

# 可以很簡單的從終端獲得輸入數據
input_string_var = input("Enter some data: ") # 返回字符串數值

# 在給變量賦值前不用提前聲明
# 習慣上變量命名是小寫,用下劃線分隔單詞
some_var = 5
some_var  # => 5

# 訪問未賦值的變量會拋出異常
# 參考流程控制一段來學習異常處理
some_unknown_var  # 拋出 NameError

# "if" 可以用作表達式,它的作用等同於 C 語言的三元運算符 "?:"
"yay!" if 0 > 1 else "nay!"  # => "nay!"

# 用列表 (list) 儲存序列
li = []
# 創建列表時也可以同時賦給元素
other_li = [4, 5, 6]

# 用append在列表最後追加元素
li.append(1)    # li現在是[1]
li.append(2)    # li現在是[1, 2]
li.append(4)    # li現在是[1, 2, 4]
li.append(3)    # li現在是[1, 2, 4, 3]
# 用pop從列表尾部刪除
li.pop()        # => 3 且li現在是[1, 2, 4]
# 把3再放回去
li.append(3)    # li變回[1, 2, 4, 3]

# 列表存取跟數組一樣
li[0]  # => 1
# 取出最後一個元素
li[-1]  # => 3

# 越界存取會造成 IndexError
li[4]  # 拋出 IndexError

# 列表有切割語法
li[1:3]    # => [2, 4]
# 取尾
li[2:]     # => [4, 3]
# 取頭
li[:3]     # => [1, 2, 4]
# 隔一個取一個
li[::2]    # =>[1, 4]
# 倒排列表
li[::-1]   # => [3, 4, 2, 1]
# 可以用三個參數的任何組合來構建切割
# li[始:終:步伐]

# 簡單的實現了單層數組的深度複製
li2 = li[:]  # => li2 = [1, 2, 4, 3] ,但 (li2 is li) 會返回 False

# 用 del 刪除任何一個元素
del li[2]   # li 現在為 [1, 2, 3]

# 刪除第一個匹配的元素
li.remove(2)  # li 現在為 [1, 3]
li.remove(2)  # 拋出錯誤 ValueError: 2 is not in the list

# 在指定索引處插入一個新的元素
li.insert(1, 2)  # li is now [1, 2, 3] again

# 獲得列表第一個匹配的值的索引
li.index(2)  # => 1
li.index(4)  # 拋出一個 ValueError: 4 is not in the list

# 列表可以相加
# 注意:li 和 other_li 的值都不變
li + other_li   # => [1, 2, 3, 4, 5, 6]

# 用 "extend()" 拼接列表
li.extend(other_li)   # li 現在是[1, 2, 3, 4, 5, 6]

# 用 "in" 測試列表是否包含值
1 in li   # => True

# 用 "len()" 取列表長度
len(li)   # => 6


# 元組類似列表,但是不允許修改
tup = (1, 2, 3)
tup[0]   # => 1
tup[0] = 3  # 拋出 TypeError

# 如果元素數量為 1 的元組必須在元素之後加一個逗號
# 其他元素數量的元組,包括空元組,都不需要
type((1))   # => <class 'int'>
type((1,))  # => <class 'tuple'>
type(())    # => <class 'tuple'>

# 列表允許的操作元組大多都可以
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
# 也可以做擴展解包
a, *b, c = (1, 2, 3, 4)  # 現在 a 是 1, b 是 [2, 3], c 是 4
# 元組周圍的括號是可以省略的
d, e, f = 4, 5, 6 # 元組 4, 5, 6 通過解包被賦值給變量 d, e, f
# 交換兩個變量的值就這麼簡單
e, d = d, e     # 現在 d 是 5,e 是 4


# 字典用來存儲 key 到 value 的映射關係
empty_dict = {}
# 初始化的字典
filled_dict = {"one": 1, "two": 2, "three": 3}

# 字典的 key 必須為不可變類型。 這是為了確保 key 被轉換為唯一的哈希值以用於快速查詢
# 不可變類型包括整數、浮點、字符串、元組
invalid_dict = {[1,2,3]: "123"}  # => 拋出 TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]}   # 然而 value 可以是任何類型

# 用[]取值
filled_dict["one"]   # => 1

# 用 keys 獲得所有的鍵。
# 因為 keys 返回一個可迭代對象,所以我們需要把它包在 "list()" 裏才能轉換為列表。
# 我們下面會詳細介紹可迭代。
# 注意: 對於版本 < 3.7 的 python, 字典的 key 的排序是無序的。你的運行結果
# 可能與下面的例子不符,但是在 3.7 版本,字典中的項會按照他們被插入到字典的順序進行排序
list(filled_dict.keys())  # => ["three", "two", "one"] Python 版本 <3.7
list(filled_dict.keys())  # => ["one", "two", "three"] Python 版本 3.7+

# 用 "values()" 獲得所有的值。跟 keys 一樣也是可迭代對象,要使用 "list()" 才能轉換為列表。
# 注意: 排序順序和 keys 的情況相同。

list(filled_dict.values())  # => [3, 2, 1] Python 版本 < 3.7
list(filled_dict.values())  # => [1, 2, 3] Python 版本 3.7+


# 用in測試一個字典是否包含一個鍵
"one" in filled_dict   # => True
1 in filled_dict   # => False

# 訪問不存在的鍵會導致 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}

# 類似字典的 keys,set 的元素也必須是不可變類型
invalid_set = {[1], 1}  # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}

# 可以把集合賦值於變量
filled_set = some_set

# 為集合添加元素
filled_set.add(5)   # filled_set 現在是 {1, 2, 3, 4, 5}
# set 沒有重複的元素
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}

# "^" 取異或集(對稱差)
{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

# 單層集合的深度複製
filled_set = some_set.copy()  # filled_set 是 {1, 2, 3, 4, 5}
filled_set is some_set        # => False

####################################################
## 3. 流程控制和迭代器
####################################################

# 先隨便定義一個變量
some_var = 5

# 這是個if語句。注意縮進在Python裏是有意義的!
# 縮進要使用 4 個空格而不是 tabs。
# 這段代碼會打印 "some_var is smaller than 10"
if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # elif 語句是可選的
    print("some_var is smaller than 10.")
else:                  # else 也是可選的
    print("some_var is indeed 10.")


"""
用 for 循環語句遍歷列表
打印:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    # 你可以使用 format() 格式化字符串並插入值
    print("{} is a mammal".format(animal))

"""
"range(number)" 返回數字列表從 0 到 number 的數字
打印:
    0
    1
    2
    3
"""
for i in range(4):
    print(i)
    
"""
"range(lower, upper)" 會返回一個包含從 lower 到 upper 的數字迭代器
prints:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print(i)

"""
"range(lower, upper, step)" 會返回一個,從 lower 到 upper、並且間隔值為 step 的迭代器。
如果 step 未傳入則會使用默認值 1
prints:
    4
    6
"""
for i in range(4, 8, 2):
    print(i)

"""
遍歷列表,並且同時返回列表裏的每一個元素的索引和數值。
prints:
    0 dog
    1 cat
    2 mouse
"""
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
    print(i, value)

"""
while 循環直到條件不滿足
打印:
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print(x)
    x += 1  # x = x + 1 的簡寫


# 用 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運行完沒有錯誤的時候這句才會運行
finally:                                 # 在任何情況下都會執行
         print("We can clean up resources here")

# 你可以使用 with 語句來代替 try/finally 對操作進行結束的操作
with open("myfile.txt") as f:
    for line in f:
        print(line)
        
# 寫入文件
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
    file.write(str(contents))        # 寫入字符串到文件

with open("myfile2.txt", "w+") as file:
    file.write(json.dumps(contents)) # 寫入對象到文件

# Reading from a file
with open("myfile1.txt", "r+") as file:
    contents = file.read()           # 從文件讀取字符串
print(contents)
# print: {"aa": 12, "bb": 21}

with open("myfile2.txt", "r+") as file:
    contents = json.load(file)       # 從文件讀取 json 對象
print(contents)
# print: {"aa": 12, "bb": 21}

# Windows 環境調用 open() 讀取文件的默認編碼為 ANSI,如果需要讀取 utf-8 編碼的文件,
# 需要指定 encoding 參數:
# open("myfile3.txt", "r+", encoding = "utf-8")


# 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()" 獲得下一個對象
next(our_iterator)  # => "one"

# 再一次調取 "next()" 時會記得位置
next(our_iterator)  # => "two"
next(our_iterator)  # => "three"

# 當迭代器所有元素都取出後,會拋出 StopIteration
next(our_iterator) # 拋出 StopIteration

# 我們還可以通過遍歷訪問所有的值,實際上,for 內部實現了迭代
our_iterator = iter(our_iterable)
for i in our_iterator:
    print(i)  # 依次打印 one, two, three

# 可以用 list 一次取出迭代器或者可迭代對象所有的元素
list(filled_dict.keys())  # => 返回 ["one", "two", "three"]
list(our_iterator)  # => 返回 [] 因為迭代的位置被保存了


####################################################
## 4. 函數
####################################################

# 用def定義新函數
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x + y    # 用 return 語句返回

# 調用函數
add(5, 6)   # => 打印 "x is 5 and y is 6" 並且返回 11

# 也可以用關鍵字參數來調用函數
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)   # 相當於 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs)   # 相當於 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs)   # 相當於 all_the_args(1, 2, 3, 4, a=3, b=4)

# 使用返回多個數值(返回值為元組類型)
def swap(x, y):
    return y, x  # 用不帶括號的元組的格式來返回多個數值
                 # (注意: 括號不需要加,但是也可以加)

x = 1
y = 2
x, y = swap(x, y)     # => x = 2, y = 1
# (x, y) = swap(x,y)  # 同上,括號不需要加,但是也可以加

    
# 函數作用域
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
(lambda x, y: x ** 2 + y ** 2)(2, 1)  # => 5

# 內置的高階函數
list(map(add_10, [1, 2, 3]))          # => [11, 12, 13]
list(map(max, [1, 2, 3], [4, 2, 1]))  # => [4, 2, 3]

list(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]

# 你也可以用這種方式實現對集合和字典的構建
{x for x in 'abcddeef' if x not in 'abc'}  # => {'d', 'e', 'f'}
{x: x**2 for x in range(5)}  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}


####################################################
## 5. 模塊
####################################################

# 導入模塊
import math
print(math.sqrt(16))  # => 4.0

# 你可以導入模塊中具體的函數
from math import ceil, floor
print(ceil(3.7))   # => 4.0
print(floor(3.7))  # => 3.0

# 你可以導入模塊中的所有的函數
# 警告: 此操作不推薦
from math import *

# 你可以對模塊名進行簡化
import math as m
math.sqrt(16) == m.sqrt(16)  # => True

# Python 模塊實質上是 Python 文件
# 你可以自己編寫自己的模塊,然後導入
# 模塊的名稱和文件名相同

# 你可以用 "dir()" 查看模塊中定義的函數和字段
import math
dir(math)

# 當你的腳本文件所在的文件夾也包含了一個名為 math.py 的 Python 文件
# 這個 math.py 文件會被代替引入,而不是引入 Python 內建模塊中的 math
# 出現這個情況的原因是本地文件夾的引入優先級要比 Python 內建庫引入優先級要高


####################################################
## 6. 類
####################################################

# 我們使用 "class" 語句來創建類
class Human:

    # 一個類的字段。 這個字段共享給這個類的所有實例。
    species = "H. sapiens"

    # 構造方法,當實例被初始化時被調用。注意名字前後的雙下劃線,這是表明這個屬性
    # 或方法對 Python 有特殊意義,但是允許用户自行定義。
    # 方法(可能是對象或者屬性) 類似: __init__, __str__,__repr__ etc
    # 都是特殊的方法
    # 你自己取名時不應該用這種格式
    def __init__(self, name):
        # 將參數賦值給實例的 name 字段
        self.name = name

        # 初始化屬性
        self._age = 0

    # 實例方法,第一個參數總是self,也就是這個實例對象
    def say(self, msg):
        print("{name}: {message}".format(name=self.name, message=msg))

    # 另一個實例方法
    def sing(self):
        return 'yo... yo... microphone check... one two... one two...'

    # 類方法,被所有此類的實例共用。
    # 第一個參數是這個類對象。
    @classmethod
    def get_species(cls):
        return cls.species

    # 靜態方法。調用時沒有實例或類的綁定。
    @staticmethod
    def grunt():
        return "*grunt*"

    # property 有點類似 getter
    # 它把方法 age() 轉換為同名並且只讀的屬性
    # 通常情況下,可以不需要編寫複雜的 getter 和 setter。
    @property
    def age(self):
        return self._age

    # 允許屬性被修改
    @age.setter
    def age(self, age):
        self._age = age

    # 允許屬性被刪除
    @age.deleter
    def age(self):
        del self._age

# 當 Python 解釋器在讀取源文件的時候,就會執行文件中所有的代碼
# 對 __name__ 的檢查可以保證這塊代碼只會在這個模塊是主程序的情況下被運行(而不是在引用時運行)
if __name__ == '__main__':
    # 
    i = Human(name="Ian")
    i.say("hi")                     # "Ian: hi"
    j = Human("Joel")
    j.say("hello")                  # "Joel: hello"
    # i 和 j 都是 Human 實例化後的對象,換一句話説,它們都是 Human 實例

    # 運行類方法 (classmethod)
    i.say(i.get_species())          # "Ian: H. sapiens"
    # 修改共享的類屬性
    Human.species = "H. neanderthalensis"
    i.say(i.get_species())          # => "Ian: H. neanderthalensis"
    j.say(j.get_species())          # => "Joel: H. neanderthalensis"

    # 運行靜態方法 (staticmethod)
    print(Human.grunt())            # => "*grunt*"

    # 實例上也可以執行靜態方法
    print(i.grunt())                # => "*grunt*"

    # 更新實例的屬性
    i.age = 42
    # 訪問實例的屬性
    i.say(i.age)                    # => "Ian: 42"
    j.say(j.age)                    # => "Joel: 0"
    # 刪除實例的屬性
    del i.age
    # i.age                         # => 這會拋出一個錯誤: AttributeError


####################################################
## 6.1 類的繼承
####################################################

# 繼承機制允許子類可以繼承父類上的方法和變量。
# 我們可以把 Human 類作為一個基礎類或者説叫做父類,
# 然後定義一個名為 Superhero 的子類來繼承父類上的比如 "species"、 "name"、 "age" 的屬性
# 和比如 "sing" 、"grunt" 這樣的方法,同時,也可以定義它自己獨有的屬性

# 基於 Python 文件模塊化的特點,你可以把這個類放在獨立的文件中,比如説,human.py。

# 要從別的文件導入函數,需要使用以下的語句
# from "filename-without-extension" import "function-or-class"

from human import Human

# 指定父類作為類初始化的參數
class Superhero(Human):
        
    # 如果子類需要繼承所有父類的定義,並且不需要做任何的修改,
    # 你可以直接使用 "pass" 關鍵字(並且不需要其他任何語句)
    # 但是在這個例子中會被註釋掉,以用來生成不一樣的子類。
    # pass

    # 子類可以重寫父類定義的字段
    species = 'Superhuman'
        
    # 子類會自動的繼承父類的構造函數包括它的參數,但同時,子類也可以新增額外的參數或者定義,
    # 甚至去覆蓋父類的方法比如説構造函數。
    # 這個構造函數從父類 "Human" 上繼承了 "name" 參數,同時又新增了 "superpower" 和
    # "movie" 參數:
    def __init__(self, name, movie=False,
                 superpowers=["super strength", "bulletproofing"]):

        # 新增額外類的參數
        self.fictional = True
        self.movie = movie
        # 注意可變的默認值,因為默認值是共享的
        self.superpowers = superpowers
                
        # "super" 函數讓你可以訪問父類中被子類重寫的方法
        # 在這個例子中,被重寫的是 __init__ 方法
        # 這個語句是用來運行父類的構造函數:
        super().__init__(name)

    # 重寫父類中的 sing 方法
    def sing(self):
        return 'Dun, dun, DUN!'

    # 新增一個額外的方法
    def boast(self):
        for power in self.superpowers:
            print("I wield the power of {pow}!".format(pow=power))


if __name__ == '__main__':
    sup = Superhero(name="Tick")

    # 檢查實例類型
    if isinstance(sup, Human):
        print('I am human')
    if type(sup) is Superhero:
        print('I am a superhero')

    # 獲取方法解析順序 MRO,MRO 被用於 getattr() 和 super()
    # 這個字段是動態的,並且可以被修改
    print(Superhero.__mro__)    # => (<class '__main__.Superhero'>,
                                # => <class 'human.Human'>, <class 'object'>)

    # 調用父類的方法並且使用子類的屬性
    print(sup.get_species())    # => Superhuman

    # 調用被重寫的方法
    print(sup.sing())           # => Dun, dun, DUN!

    # 調用 Human 的方法
    sup.say('Spoon')            # => Tick: Spoon

    # 調用 Superhero 獨有的方法
    sup.boast()                 # => I wield the power of super strength!
                                # => I wield the power of bulletproofing!

    # 繼承類的字段
    sup.age = 31
    print(sup.age)              # => 31

    # Superhero 獨有的字段
    print('Am I Oscar eligible? ' + str(sup.movie))


####################################################
## 6.2 多重繼承
####################################################

# 定義另一個類
# bat.py
class Bat:

    species = 'Baty'

    def __init__(self, can_fly=True):
        self.fly = can_fly

    # 這個類同樣有 say 的方法
    def say(self, msg):
        msg = '... ... ...'
        return msg

    # 新增一個獨有的方法
    def sonar(self):
        return '))) ... ((('

if __name__ == '__main__':
    b = Bat()
    print(b.say('hello'))
    print(b.fly)

# 現在我們來定義一個類來同時繼承 Superhero 和 Bat
# superhero.py
from superhero import Superhero
from bat import Bat

# 定義 Batman 作為子類,來同時繼承 SuperHero 和 Bat
class Batman(Superhero, Bat):

    def __init__(self, *args, **kwargs):
        # 通常要繼承屬性,你必須調用 super:
        # super(Batman, self).__init__(*args, **kwargs)
        # 然而在這裏我們處理的是多重繼承,而 super() 只會返回 MRO 列表的下一個基礎類。
        # 因此,我們需要顯式調用初始類的 __init__
        # *args 和 **kwargs 傳遞參數時更加清晰整潔,而對於父類而言像是 “剝了一層洋葱”
        Superhero.__init__(self, 'anonymous', movie=True,
                           superpowers=['Wealthy'], *args, **kwargs)
        Bat.__init__(self, *args, can_fly=False, **kwargs)
        # 重寫了 name 字段
        self.name = 'Sad Affleck'

    def sing(self):
        return 'nan nan nan nan nan batman!'


if __name__ == '__main__':
    sup = Batman()

    # 獲取方法解析順序 MRO,MRO 被用於 getattr() 和 super()
    # 這個字段是動態的,並且可以被修改
    print(Batman.__mro__)       # => (<class '__main__.Batman'>,
                                # => <class 'superhero.Superhero'>,
                                # => <class 'human.Human'>,
                                # => <class 'bat.Bat'>, <class 'object'>)

    # 調用父類的方法並且使用子類的屬性
    print(sup.get_species())    # => Superhuman

    # 調用被重寫的類
    print(sup.sing())           # => nan nan nan nan nan batman!

    # 調用 Human 上的方法,(之所以是 Human 而不是 Bat),是因為繼承順序起了作用
    sup.say('I agree')          # => Sad Affleck: I agree

    # 調用僅存在於第二個繼承的父類的方法
    print(sup.sonar())          # => ))) ... (((

    # 繼承類的屬性
    sup.age = 100
    print(sup.age)              # => 100

    # 從第二個類上繼承字段,並且其默認值被重寫
    print('Can I fly? ' + str(sup.fly)) # => Can I fly? False


####################################################
## 7. 高級用法
####################################################

# 用生成器(generators)方便地寫惰性運算
def double_numbers(iterable):
    for i in iterable:
        yield i + i

# 生成器只有在需要時才計算下一個值。它們每一次循環只生成一個值,而不是把所有的
# 值全部算好。
#
# range的返回值也是一個生成器,不然一個1到900000000的列表會花很多時間和內存。
#
# 如果你想用一個Python的關鍵字當作變量名,可以加一個下劃線來區分。
range_ = range(1, 900000000)
# 當找到一個 >=30 的結果就會停
# 這意味着 `double_numbers` 不會生成大於30的數。
for i in double_numbers(range_):
    print(i)
    if i >= 30:
        break
# 你也可以把一個生成器推導直接轉換為列表
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
print(gen_to_list)  # => [-1, -2, -3, -4, -5]


# 裝飾器(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 :(

想繼續學嗎?

在線免費材料(英文)

  • Automate the Boring Stuff with Python
  • Ideas for Python Projects
  • The Official Docs
  • Hitchhiker’s Guide to Python
  • Python Course
  • Free Interactive Python Course
  • First Steps With Python
  • A curated list of awesome Python frameworks, libraries and software
  • 30 Python Language Features and Tricks You May Not Know About
  • Official Style Guide for Python
  • Python 3 Computer Science Circles
  • Dive Into Python 3
  • A Crash Course in Python for Scientists
  • Python Tutorial for Intermediates
  • Build a Desktop App with Python

書籍(也是英文)

  • Programming Python
  • Dive Into Python
  • Python Essential Reference

有建議?或者發現什麼錯誤?在 Github 上開一個 issue,或者發起 pull request!

原著 Louie Dinh,並由 1 個好心人修改。
© 2022 Louie Dinh, Steven Basart, Andre Polykanine
Translated by: Geoff Liu Maple
本作品採用 CC BY-SA 3.0 協議進行許可。

user avatar susouth 頭像
1 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.