SlideShare a Scribd company logo
1 of 72
Python入門:5大概念初心者必備
Derek Lee
2021/11/18
Agenda
你該知道Python的慣例
初探python資料結構
什麼是if-else, for , while
Code能重複用的函式
類別(class)是何物
縮排(Indentation)
 Python 程式碼執行方式:
‘行’為單位
 上下, 左右
 如何管理區塊程式碼(block code)?
 縮排
 優點
 tab或4個space(官方建議),不建議混用
應用場合:迴圈(for/while)、條件式(if)、函式(function)、類別(class)
def order_meal(meal):
total = 0
while True:
ordered_meal = input('請點餐: ')
if ordered_meal == '':
break
elif ordered_meal in meal:
total = total + meal[ordered_meal]
print(f"{ordered_meal} {meal[ordered_meal]}元, 總金額{total}")
elif ordered_meal not in meal:
print(f'我們沒有提供{ordered_meal}')
print(f"您帳單為{total}元")
meal = {"三明治": 30, "漢堡": 40, "奶茶": 25}
order_meal(meal)
賦值(assignment)
Dynamic assignment
x = 10
print(x)
# 10
# x 參照(reference) 10
x = 10
x = "abc"
x = [1, 2, 3]
print(x)
# [1, 2, 3]
10
“abc”
[1, 2, 3]
x
賦值(assignment)
 變數型別受參照物件的影響
 type(物件)  檢查型別
x = 10
print(type(x))
x = “abc”
print(type(x))
x = [1, 2, 3]
print(type(x))
10
“abc”
[1, 2, 3]
x
<class 'int'>
<class 'str'>
<class 'list'>
賦值(assignment)
 在呼叫前完成assignment
x = 10
print(x + y)
y = 20
# NameError: name 'y' is not defined
x = 10
y = 20
print(x + y)
賦值(assignment)
 每個物件在記憶體都有自己的家
 id() 查記憶體位置
x = 10
print(id(10))
print(id(x))
10
“abc”
[1, 2, 3]
x
1879242816
40148480
40226344
賦值(assignment)
 命名規則
 變數名避開內建(built-in)函式
 導致內建函式無法執行該有的功能
x = 100
print = 19
print(x)
# TypeError: 'int' object is not callable
x = 100
print_ = 19
print(x)
# 100
賦值(assignment)
 命名規則
 第一個字母不能為數字; 可為英文字母或underscore( _ )
 Case Sensitive
3x = 1000
print(3x)
#SyntaxError: invalid syntax
a = "cake"
Print = "cake"
print(a)
# cake
string(字串)
 字元序列(Sequence)
 字元有順序
 資料不可變
 如何建立string?
 如何計算string長度?
x = 'anx'
y = "hsb"
print(type(x), type(y))
# <class 'str'> <class 'str'>
x = "123456"
print(len(x)) # 6
string(字串)
 str() 進行型別轉換
x = 10
print(type(x)) # <class 'int'>
y = str(x)
print(type(y)) # <class 'str'>
string(字串)
數字字串 int() 數字
x = '10'
y = int(x)
print(type(y))
# <class 'int'>
x = 'a'
y = int(x)
print(y)
print(type(y))
#ValueError: invalid literal for int() with base 10: 'a'
string(字串)
 可透過slicing取出特定字元
 無法透過slicing更換字元
x = "hello world"
y = x[0:5]
print(y)
# hello
x = "hello world"
x[0:5] = "wonderful"
print(x)
# TypeError: 'str' object does not support item assignment
string(字串)_常用method
 string.replace(old, new, count)
 new取代old,
 count是指有多少old的字元要被取代(optional, 預設值=all)
 回傳新物件
x = "Hello World"
print(x.replace("l", "99")) # He9999o Wor99d
print(x.replace("l", "99",2)) # He9999o World
print(x) # Hello World
string(字串)_常用method
 字串切割並存成list
 string.split(separator, maxsplit)
 separator:分割符號,預設值為空格
 maxsplit:分割次數;預設值為全部分割
x = "I Love Python and Hello world"
print(x.split()) # ['I', 'Love', 'Python', 'and', 'Hello', 'world']
print(x.split(" ", 2)) # ['I', 'Love', 'Python and Hello world']
string format
可透過 + 或空格串接字串
print("Hello" + " world")
print("Hello " "world")
# Hello world
那如果要串接數個字串或串接時要進行額外處理,改怎做呢?
我們可用兩種string format處理
 string.format
 f-string
string.format
 語法:"{},{}".format(v1, v2)
 "{},{}"稱為格式化字串、{}稱為格式化的位置參數
print("{} is the best {} in the {}".format("Python", "language", "world"))
# Python is the best language in the world
位置參數
print("{} * {} = {}".format(2, 3, 2*3))
# 2 * 3 = 6
位置參數指定
print("{0} is the best {1} in the {2}".format("Python", "language", "world"))
# Python is the best language in the world
print("{1} is the best {2} in the {0}".format("Python", "language", "world"))
# language is the best world in the Python
string.format
 語法:"{},{}".format(v1, v2)
 "{},{}"稱為格式化字串、{}稱為格式化的位置參數
參數名指定
print("{volum} {fruit}s cost {price} dollars".format(fruit = "apple", price = 100, volum = 10))
# 10 apples cost 100 dollars
同時使用:位置參數在前,參數名指定在後
print("{2} {fruit}s cost {price} dollars".format(fruit = "apple", price = 100, 10))
# SyntaxError: positional argument follows keyword argument
print("{0} {fruit}s cost {price} dollars".format(10, fruit = "apple", price = 100))
# 10 apples cost 100 dollars
f-string
 String Interpolation(字串插值) , 在字串中進行格式化
 語法: f“{x1} {x2}”,其中f大小寫皆可
fruit = "apple"
print(f"My favorite fruit is {fruit}")
# My favorite fruit is apple
 {} 可放入有效的expression
print(f"2*6 is equal to {2*6}") # 2*6 is equal to 12
name = "bob"
print(f"My name is {name.upper()}") # My name is BOB
slicing
 在有序資料中,取出特定的物件。
 有序資料:string, list, tuple
 有序資料的index
 從 0 開始算
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
slicing
 語法 [start : end : step]
 start: 從哪開始取
 end: 到哪截止(但不包含end)
 step:(optional), 間隔, 如為負數則從最後元素反向取物
x = "HelloPython"
print(len(x)) # 11
print(x[0:10]) # HelloPytho
print(x[0:]) # HelloPython
print(x[1:6:2]) # elP
x = “HelloPython”
print(x[-1: :-1]) # nohtyPolleH
print(x[::-1]) # nohtyPolleH
print(x)
初探Python資料結構
 list
 tuple
 dict
 set
list
 有序資料
 元素可為任意資料型態(type)
 用 []建立
a = [{"a" : 1}, 'b', 1]
print(a)
# [{'a': 1}, 'b', 1]
 用list()進行型別轉換
a = (1, 2, 3, 4, 5) # tuple
print(list(a)) # [1, 2, 3, 4, 5]
b = "12345"
print(list(b)) # ['1', '2', '3', '4', '5']
list
 用len()查詢list元素個數
a = [1, 2, 3, 4, 5]
print(len(a)) # 5
 重複串列所有元素
a = [1, 2, 3, 4, 5]
print(a*3)
# [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
list 常用方法(method)
 用append在串列最後一元素接續新增單一物件
 list.append(element)
a = [] # 空集合
a.append(100)
print(a) # [100]
 大部分method會修改原串列(existing list)
 如用變數接收,結果會是None
b = a.append(100)
print(b) # None
list 常用方法(method)
 那麼要如何把串列個別元素新增到c串列中呢?
 list.extend(iterable)
c = [1,2,3]
c.append([99,88,77])
print(c)
猜想的結果 [1, 2, 3, 99, 88, 77]
實際的結果 [1, 2, 3, [99, 88, 77]]
c = [1,2,3]
c.extend([99,88,77])
print(c)
#[1, 2, 3, 99, 88, 77]
list 常用方法(method)
 用index查詢物件的位置
 list.index(element)
 用count計算指定物件在串列中出現的次數
 list.count(element)
a = ['a', 'b', 'c', 'd']
print(a.index('c'))
# 2
a = ['a', 'b', 'c', 'd', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
print(a.count('c'))
# 12
list 常用方法(method)
 用sort進行排序
 list.sort(reverse=False, key=func)
1.預設值reverse=False(小到大), reverse=True如要大到小排序
2.key可自訂函式作為排序判斷
a = [1, 3, 4, 7, 2, 5, 9, 0, 11, 6]
a.sort(reverse=False) # 亦可寫 a.sort()
print(a)
# [0, 1, 2, 3, 4, 5, 6, 7, 9, 11]
list 常用方法(method)
用join把串列整併形成字串(string)
 ‘ ’.join(iterable); ‘’可放入元素間分隔符號
word_list = ['Hello', 'world']
word_str = ' '.join(word_list)
word_str2 = ' & '.join(word_list)
print(word_str) # Hello world
print(word_str2) # Hello & world
slicing
 用reverse將串列元素進行反轉,未進行排序
 list.reverse()
a = [1, 9, 100, 3, 7, 345]
a.reverse()
print(a) # [345, 7, 3, 100, 9, 1]
 如何用slicing反轉串列的資料呢?
 list[ : : -1]
a = [1, 9, 100, 3, 7, 345]
b = a[::-1]
print(b) # [345, 7, 3, 100, 9, 1]
print(a) # [1, 9, 100, 3, 7, 345]
slicing
我們想複製一份有序資料進行修改,
那該怎麼做呢?
x = [1,2,3,4]
y = x
print(id(x)) # 37998120
print(id(y)) # 37998120
y[0] = 9999
print(y) #[9999, 2, 3, 4]
print(x) #[9999, 2, 3, 4]
複製後修改,如不影響原串列,
那該怎麼做呢?
>> 語法 list[:]
x = [1,2,3,4]
y = x[:]
print(y) # [1, 2, 3, 4]
y[0] = 9999
print(y) # [9999, 2, 3, 4]
print(x) # [1, 2, 3, 4]
tuple
 有序資料但資料不可變
 用()建立
x = () # 空tuple
x = (1, 2, 3, 4)
 如何建立單一個元素的tuple
x = (1)
print(x) # 1 is a int type
我們直覺建立 正確:(元素, )
x = (1, )
print(x) # (1, )
tuple with slicing
 slicing僅能讀取資料,不能修改,否則出現TypeError。
x = (1, 2, 3, 4)
print(x[2]) # 3
x = (1, 2, 3, 4)
x[2] = "aaa"
print(x)
# TypeError: 'tuple' object does not support item assignment
tuple 常用方法(method)
 用count計算item出現的次數
 tuple.count(item)
x = (1, 2, 3, 4, 1, 1, 1, 1, 1)
print(x.count(1))
# 6
 用index找出item的位置
 tuple.index(item)
x = (1, 2, 3, 4, 5, "a")
print(x.index("a"))
# 5
dict
 查字典
 {key1: value1, key2: value2}
 key  不可變的物件, 如str, number, tuple
 value  任意物件
 如使用tuple當key, 要確保每個元素都是不可變
x = {1 :'a', 'b' : 2, 'c' : [1,2,3]}
print(x)
# {1: 'a', 'b': 2, 'c': [1, 2, 3]}
y = {([1,2,3], 4, 5):1, 'b':2}
print(y)
# TypeError: unhashable type: 'list'
dict
 資料有重複key,後面key的value取代前面的
z = {'a':1, 'b':2, 'a':"python", 2:'abc', 'a':9999888}
print(z)
# {'a': 9999888, 'b': 2, 2: 'abc'}
 如何在原有dict新增key:value?
 [new_key] = value
z = {'a':1, 'b':2, 'a':"python", 2:'abc', 'a':9999888}
print(z)
z["apple"] = 1094
print(z)
# {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094}
dict 常用方法(method)
 dict[key] = value, 除新增key:value, 也可更新key:value
z = {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094}
z["a"] = "hello"
print(z)
# {'a': 'hello', 'b': 2, 2: 'abc', 'apple': 1094}
 dict.update(iterable)
z = {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094}
z.update({'a': 'hello'})
print(z) # {'a': 'hello', 'b': 2, 2: 'abc', 'apple': 1094}
z.update(({'watch' : 2039}))
print(z) # {'a': 'hello', 'b': 2, 2: 'abc', 'apple': 1094, 'watch': 2039}
dict 常用方法(method)
 用key取值,語法為dict[key1],得對應的value1
z = {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094}
print(z["apple"]) # 1094
 上述方法取值的缺點: key若不存在, 會產生KeyError
z = {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094}
print(z["Apple"]) # KeyError: 'Apple'
 dict.get(key, value=None)
x = {1 :'a', 'b' : 2, 'c' : [1,2,3]}
print(x.get('d')) # None
print(x.get('d', 2)) # 2
dict 常用方法(method)
 當我們想取用的key:value不在dict,不想出現KeyError,
但希望同步建一組,該怎做?
 dict.setdefault(key,value)
x = {1 :'a', 'b' : 2, 'c' : [1,2,3]}
print(x.setdefault(1,100)) # a
print(x.setdefault('d',"hello world")) # hello world
print(x) # {1: 'a', 'b': 2, 'c': [1, 2, 3], 'd': 'hello world'}
dict 常用方法(method)
 dict.keys() 取用所有keys
 dict.values() 取用所有values
 dict.items() 取用所有key/value
x = {'a': 199, 'b': "Hello", 'c':[1,2,3]}
print(x.keys())
# dict_keys(['a', 'b', 'c'])
print(x.values())
# dict_values([199, 'Hello', [1, 2, 3]])
print(x.items())
#dict_items([('a', 199), ('b', 'Hello'), ('c', [1, 2, 3])])
set
 無序的資料結構
 元素唯一性
 slicing不適用
 用{}建立
 {} 是空字典; set()是空集合
x = {1, 2, 3, 4}
print(type(x)) # <class 'set'>
x = {1, 1, 1, 1, 1, 1}
print(x) # {1}
x = { }
print(type(x))
# <class 'dict'>
x = {1, 2, 3, 4}
print(x[0])
# TypeError: 'set' object is not subscriptable
x = {1, 2, 3, 4}
x[0] = 2
print(x)
# TypeError: 'set' object does not support item assignment
if-else條件式
 if 條件式成立就執行程式碼,否則就執行else所屬的程式碼
if 條件式成立:
執行code
else:
執行code
x = 100
if x >= 100:
print("數值大於等於100")
else:
print("數值小於100")
# 數值大於等於100
if-else條件式
 elif 多種情況需判別
if 條件式成立:
執行code
elif 條件式成立:
執行code
else:
執行code
age = 10
if age < 0:
print("年齡必須大於0")
elif age > 18:
print("你可以考駕照了")
else :
print("尚未到法定年齡")
# 尚未到法定年齡
while loop
 條件式成立,執行所屬的程式碼,如否,跳出while迴圈
n = 1
nums = []
while n < 5:
nums.append(n)
n += 1
print(nums)
# [1, 2, 3, 4]
while 條件式成立:
執行code
for loop
 概念為item走訪可迭代(iterable)物件,其中可迭代的物件有
string, list, dict, tuple, set等,然後回傳想要的結果。
for item in iterable:
執行code
b = "12345"
print(list(b)) # ['1', '2', '3', '4', '5']
b = "12345"
nums = []
for num in b:
nums.append(num)
print(nums)
# ['1', '2', '3', '4', '5']
range(start, end, step)
 讓item走訪某連續區間的數字
 數值區間會在for迴圈走訪時動態產生
 range(start, end, step)
 start: 預設值為0
 end:執行時被排除
 step:要間隔多少
 搭配list快速產生數值串列
x = range(1, 10)
print(list(x))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
x = list(range(1, 10, 2))
print(x)
# [1, 3, 5, 7, 9]
for loop
 如何用for loop + range產出一樣的結果?
x = range(1, 10)
print(list(x))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
nums = []
for num in range(1, 10):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
list comprehension
 語法: [運算式 for 變數 in iterable if 條件成立]
nums = [num for num in range(1, 10)]
print(nums)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
 簡潔, 可讀性降低
y = [num**2 for num in range(20) if num >10]
print(y)
#[121, 144, 169, 196, 225, 256, 289, 324, 361]
y = []
for num in range(20):
if num > 10:
y.append(num**2)
print(y)
# [121, 144, 169, 196, 225, 256, 289, 324, 361]
break / continue
 break 取消迴圈
 continue 略過後面程式碼,同步進入下一個迴圈
while True:
value = input(“enter integer number (q when exit): ”)
if value == “q” :
break # 離開迴圈
value = int(value)
if value % 2 != 0:
continue #跳過,在進入下一個迴圈
print("the even value is", value)
# 執行結果如下
# enter integer number (q when exit): 1
# enter integer number (q when exit): 2
# the even value is 2
# enter integer number (q when exit): q
有同樣功能該怎做…….?
 ctrl + c / ctrl + v
#設定x, y變數值,印出加總結果
x = 10
y = 20
print(x + y) # 30
#再次設定x, y變數值,印出加總結果
x = 100
y = 299
print(x +y) # 399
如有數個地方使用同功能,難道要一直複製貼上?
如這功能有調整,複製的地方全要同步手動調?
函式(function)
 整併重複使用&功能相同的程式碼
 組成:
 函式名:小寫, _ 連結兩個以上英文字
 參數
 block code
def function_name(parameter,..):
block code
print
function_name()
def function_name(parameter,..):
block code
return
result = function_name()
print(result)
有同樣功能該怎做…….?
 ctrl + c / ctrl + v
#設定x, y變數值,印出加總結果
x = 10
y = 20
print(x + y) # 30
#再次設定x, y變數值,印出加總結果
x = 100
y = 299
print(x +y) # 399
 透過function改寫
def add_value(x, y):
return x + y
result = add_value(10, 20)
print(result)
def add_value(x, y):
print(x + y)
add_value(10, 20)
函式(function)
 參數(Parameter)指在定義函數時的形式變數,數值未定
 引述(Argument)呼叫投入的值
def add_value(x, y):
print(x + y)
add_value(10, 20)
參數
引數
 定義有參數,呼叫必有引數
def add_value(x, y):
return x + y
result = add_value(10)
print(result) # 30
#TypeError: add_value() missing 1 required positional argument: 'y'
函式(function)
 定義有參數,呼叫必有引數
 設定預設值,可避免沒引數造成TypeError
def favorite_food(food = "apple"):
print(f"My favorite food is {food}")
favorite_food("orange")
# My favorite food is orange
favorite_food()
# My favorite food is apple
引數要如何傳遞到函式呢?
 利用參數位置進行傳遞
def subtraction_value(x, y):
return x - y
print(subtraction_value(10, 20)) # -10
print(subtraction_value(20, 10)) # 10
 keyword argument :引數賦予參數名
def subtraction_value(x, y):
return x - y
print(subtraction_value(x = 10, y = 20)) # -10
print(subtraction_value(y = 20, x = 10)) # -10
一個參數對應多個引數
 *args 接收位置參數, 形成tuple
def summation(*args):
return sum(args)
result = summation(1, 2, 3, 4, 5, 6)
print(result) # 21
**kwargs keyword arguments縮寫,形成dict
def kwargs_example(**x):
print(x)
print(type(x))
kwargs_example(a = 1, b = 2, c = "HappyCoding")
# {'a': 1, 'b': 2, 'c': 'HappyCoding'}
# <class 'dict'>
一個參數對應多個引數
def mix_example(x, y, z, w = "defult", *args, **kwargs):
print(x)
print(y)
print(z)
print(w)
print(args)
print(kwargs)
mix_example("apple", 20, [1,2,3], a = 100, greeting = "hello world")
# apple
# 20
# [1, 2, 3]
# defult
# ()
# {'a': 100, 'greeting': 'hello world'}
參數順序:位置參數、預設值、*args、**kwargs
實際案例
 假設餐廳提供三種餐點
 三明治, 50元
 咖啡, 40元
 沙拉, 30元
 寫oder_meal(), 讓使用者輸入餐
點, 統計點餐的總金額, 直到使用
者直接按enter離開
餐點儲存在dict
如使用者輸入菜單上沒有的餐點,
顯示錯誤訊息
使用者點餐結束後,顯示總金額
meal = {"三明治": 50,
"咖啡": 40,
"沙拉": 30
}
def order_meal(meal):
total = 0
while True:
ordered_meal = input('請點餐: ')
if ordered_meal == '':
break
elif ordered_meal in meal:
total = total + meal[ordered_meal]
print(f"{ordered_meal} {meal[ordered_meal]}元, 總金額{total}")
elif ordered_meal not in meal:
print(f'我們沒有提供{ordered_meal}')
print(f"您帳單為{total}元")
# order_meal(meal)
order_meal(meal)
題目來源:Python刷提鍛鍊班
class
 OOP(Object Oriented Programming)
程式碼可再利用(reuse)
易於維護與問題排除(debugging)
針對專案需求進行客製化。
 Python利用類別(class)實現OOP
 Python中所有東西都是物件(object)
 int, list, tuple, string, …….
class
 類別為物件的設計藍圖,同一個類別的物件會有相同的屬性與操作
方法(method)。
class Human:
pass
 屬性(Attribute):為類別會有的特徵。
 操作方式(Method):為類別操作的方式,期達到我們想要的結果。
Human
Attribute
Method
姓名, 年齡, 髮色, 身高, …….
走, 跳, 說話, ……..
class
 屬性(Attribute):為類別會有的特徵。
 操作方式(Method):為類別操作的方式,期達到我們想要的結果。
class Human:
def __init__(self,name,age): # Method
self.name = name # Attribute
self.age = age
def sound(self, voice):
return f"{self.name} has the {voice} sound"
設定初始值
 使用時機:每個實例物件皆有共同的屬性,以降低冗長的程式碼
 區分同類別的實例化物件,指在實例化過程中給予不同的屬性值,
每個實例物件就會產生差異。
class Human:
def __init__(self,name,age):
self.name = name
self.age = age
實例化(Instantiate)
 從類別物件創造出實例物件的過程
 如何建立實例化物件?
 透過呼叫類別物件、並予以命名。
class Human:
def __init__(self,name,age):
self.name = name
self.age = age
def sound(self, voice):
return f"{self.name} has the {voice} sound"
#建立實例化物件
king = Human("king", 22)
queen = Human("Queen", 20)
如何取用類別的屬性與method?
取用屬性:
instance.attribute
取用method:
instance.method()
class Human:
def __init__(self,name,age):
self.name = name
self.age = age
def sound(self, voice):
return f"{self.name} has the {voice} sound"
king = Human("king", 22)
queen = Human("Queen", 20)
print(king.name) # King
print(king.age) # 22
print(king.sound("HAHA")) # king has the HAHA sound
如何取用類別的屬性與method?
更改實例物件屬性資料,僅影響自身的屬性值
class Human:
def __init__(self,name,age):
self.name = name
self.age = age
def sound(self, voice):
return f“{self.name} has the {voice} sound”
king = Human(“king”, 22)
queen = Human(“Queen”, 20)
queen.name = “Elsa”
queen.age = 21
print(“After changing name is ”, king.name) # After changing name is king
print(“After changing age is ”,king.age) # After changing age is 22
print(“After changing name is ”,queen.name) # After changing name is Elsa
print(“After changing age is ”,queen.age) # After changing age is 21
inheritance
 當你發現寫過類
別的程式碼在新
類別仍然可用,
你會怎麼做?
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
d = Animal("Doff", 2)
print("{} is {} years old".format(d.name, d.age)) # Doff is 2 years old
print(d.sound("bark")) # bark
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
poppy = Dog("Poppy", 3)
print("{} is {} years old".format(poppy.name, poppy.age)) # Poppy is 3 years old
print(poppy.sound("bark")) # bark
如何解決呢?
繼承(inheritance)
inheritance
 從既有類別(Parent Class)中創造出新的子類別(Child Class),新的子
類別承襲了既有類別的所有屬性與method
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
pass # 雖然無程式碼,但Python仍會執行
poppy = Dog("Poppy", 3)
print("{} is {} years old".format(poppy.name, poppy.age)) #Poppy is 3 years old
print(poppy.sound("bark")) #bark
inheritance
 Child class 如何取用 Parent class的方法(method)?
 super().method
 ParentClass.method
 明確知道取用哪個Parent Class
 缺乏彈性, 當Parent Class改名, 就要逐一修改
inheritance_ super().method
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
super().__init__(name,age)
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
poppy = Dog("Poppy", 3, "Brown")
print("{} is {} years old and the color is {}".format(poppy.name, poppy.age, poppy.color))
# Poppy is 3 years old and the color is Brown
print(poppy.sound("bark"))
# Poppy has the bark sounds
inheritance_ ParentClass.method
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
Animal.__init__(self, name,age) # 類別名稱後面不用加()、第一個參數須為self
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
poppy = Dog("Poppy", 3, "Brown")
print("{} is {} years old and the color is {}".format(poppy.name, poppy.age, poppy.color))
# Poppy is 3 years old and the color is Brown
print(poppy.sound("bark")) # Poppy has the bark sounds
inheritance with Override
 Childe class 與 Parent
class有相同的方法
(method)名,實質內容不
同
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
super().__init__(name,age)
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
kity = Animal("Kity", 6)
poppy = Dog("Poppy", 3, "Brown")
print(f"{poppy.name} is {poppy.age} years old and the color is {poppy.color}")
# Poppy is 3 years old and the color is Brown
print(poppy.sound("bark")) # Poppy has the bark sounds
print(kity.sound("Haha....")) # Haha....
inheritance with Add
 子類別建立自己的操
作方式(mehotd)
 僅適用子類別
 Parent class呼叫會
出現錯誤
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self, voice):
return voice
class Dog(Animal):
def __init__(self, name, age, color):
Animal.__init__(self, name,age) # 類別名稱後面不用加()、第一個參數須為self
self.color = color
def sound(self, voice):
return f"{self.name} has the {voice} sounds"
def run(self):
return "Running fast"
doff = Animal("Doff",1)
poppy = Dog("Poppy", 3, "Brown")
print(poppy.run()) # Running fast
print(doff.run()) # AttributeError: 'Animal' object has no attribute 'run'

More Related Content

What's hot (20)

Ch8
Ch8Ch8
Ch8
 
Ch12 教學
Ch12 教學Ch12 教學
Ch12 教學
 
Appendix B 範例
Appendix B 範例Appendix B 範例
Appendix B 範例
 
Ch7 範例
Ch7 範例Ch7 範例
Ch7 範例
 
Python learn guide
Python learn guidePython learn guide
Python learn guide
 
Python元組,字典,集合
Python元組,字典,集合Python元組,字典,集合
Python元組,字典,集合
 
Python串列資料應用
Python串列資料應用Python串列資料應用
Python串列資料應用
 
R intro 20140716-basic
R intro 20140716-basicR intro 20140716-basic
R intro 20140716-basic
 
Ch9 教學
Ch9 教學Ch9 教學
Ch9 教學
 
Ch4
Ch4Ch4
Ch4
 
第5章数组
第5章数组第5章数组
第5章数组
 
Ch11
Ch11Ch11
Ch11
 
Appendix B 教學
Appendix B 教學Appendix B 教學
Appendix B 教學
 
Ch7
Ch7Ch7
Ch7
 
Bash shell script 教學
Bash shell script 教學Bash shell script 教學
Bash shell script 教學
 
Python速成指南
Python速成指南Python速成指南
Python速成指南
 
Python 入門
Python 入門 Python 入門
Python 入門
 
Ch5
Ch5Ch5
Ch5
 
Ch9
Ch9Ch9
Ch9
 
Python變數與資料運算
Python變數與資料運算Python變數與資料運算
Python變數與資料運算
 

Similar to Python入門:5大概念初心者必備 2021/11/18

Java 開發者的函數式程式設計
Java 開發者的函數式程式設計Java 開發者的函數式程式設計
Java 開發者的函數式程式設計Justin Lin
 
Python学习笔记
Python学习笔记Python学习笔记
Python学习笔记Lingfei Kong
 
ncuma_pylab.pptx
ncuma_pylab.pptxncuma_pylab.pptx
ncuma_pylab.pptxNCU MCL
 
20161209-Julia Taiwan first meetup-julia語言入門
20161209-Julia Taiwan first meetup-julia語言入門20161209-Julia Taiwan first meetup-julia語言入門
20161209-Julia Taiwan first meetup-julia語言入門岳華 杜
 
Python basic - v01
Python   basic - v01Python   basic - v01
Python basic - v01ssuser5e7722
 
Learning python in the motion picture industry by will zhou
Learning python in the motion picture industry   by will zhouLearning python in the motion picture industry   by will zhou
Learning python in the motion picture industry by will zhouWill Zhou
 
页游开发中的 Python 组件与模式
页游开发中的 Python 组件与模式页游开发中的 Python 组件与模式
页游开发中的 Python 组件与模式勇浩 赖
 
ncuma_SymPy符號運算套件.pptx
ncuma_SymPy符號運算套件.pptxncuma_SymPy符號運算套件.pptx
ncuma_SymPy符號運算套件.pptxNCU MCL
 
Num py basic(2) - v01
Num py   basic(2) - v01Num py   basic(2) - v01
Num py basic(2) - v01ssuser5e7722
 
Sql培训 (1)
Sql培训 (1)Sql培训 (1)
Sql培训 (1)jhao niu
 
Rde packagean zhuang_ji_ji_ben_cao_zuo_
Rde packagean zhuang_ji_ji_ben_cao_zuo_Rde packagean zhuang_ji_ji_ben_cao_zuo_
Rde packagean zhuang_ji_ji_ben_cao_zuo_vinsin27
 

Similar to Python入門:5大概念初心者必備 2021/11/18 (20)

Java 開發者的函數式程式設計
Java 開發者的函數式程式設計Java 開發者的函數式程式設計
Java 開發者的函數式程式設計
 
Ch5 教學
Ch5 教學Ch5 教學
Ch5 教學
 
Ch5
Ch5Ch5
Ch5
 
Python学习笔记
Python学习笔记Python学习笔记
Python学习笔记
 
Scala+RDD
Scala+RDDScala+RDD
Scala+RDD
 
ncuma_pylab.pptx
ncuma_pylab.pptxncuma_pylab.pptx
ncuma_pylab.pptx
 
20161209-Julia Taiwan first meetup-julia語言入門
20161209-Julia Taiwan first meetup-julia語言入門20161209-Julia Taiwan first meetup-julia語言入門
20161209-Julia Taiwan first meetup-julia語言入門
 
Python basic - v01
Python   basic - v01Python   basic - v01
Python basic - v01
 
Python 温故
Python 温故Python 温故
Python 温故
 
Ch10 習題
Ch10 習題Ch10 習題
Ch10 習題
 
Ch4 教學
Ch4 教學Ch4 教學
Ch4 教學
 
Learning python in the motion picture industry by will zhou
Learning python in the motion picture industry   by will zhouLearning python in the motion picture industry   by will zhou
Learning python in the motion picture industry by will zhou
 
页游开发中的 Python 组件与模式
页游开发中的 Python 组件与模式页游开发中的 Python 组件与模式
页游开发中的 Python 组件与模式
 
ncuma_SymPy符號運算套件.pptx
ncuma_SymPy符號運算套件.pptxncuma_SymPy符號運算套件.pptx
ncuma_SymPy符號運算套件.pptx
 
Num py basic(2) - v01
Num py   basic(2) - v01Num py   basic(2) - v01
Num py basic(2) - v01
 
Sql培训 (1)
Sql培训 (1)Sql培训 (1)
Sql培训 (1)
 
Ppt 78-100
Ppt 78-100Ppt 78-100
Ppt 78-100
 
Ppt 1-50
Ppt 1-50Ppt 1-50
Ppt 1-50
 
Ppt 78-100
Ppt 78-100Ppt 78-100
Ppt 78-100
 
Rde packagean zhuang_ji_ji_ben_cao_zuo_
Rde packagean zhuang_ji_ji_ben_cao_zuo_Rde packagean zhuang_ji_ji_ben_cao_zuo_
Rde packagean zhuang_ji_ji_ben_cao_zuo_
 

Python入門:5大概念初心者必備 2021/11/18