SlideShare a Scribd company logo
Python入門:5大概念初心者必備
Derek Lee
2021/11/18
我是誰?
跨域自學者
撰寫技術筆記
2
Agenda
概念一:你需知道index, string, slicing
概念二:初探python資料結構
概念三:什麼是if-else, for , while
概念四: Code能重複用的函式
概念五:類別(class)是何物
3
index(索引值)
 在有序資料中,元素的順序。
 有序資料:string, list, tuple
 有序資料的index
 從 0 開始算
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
4
string(字串)
 字元序列(Sequence)
 字元有順序
 資料不可變
 如何建立string?
 如何計算string長度?
x = 'anx'
y = "hsb"
print(type(x), type(y))
# <class 'str'> <class 'str'>
x = "123456"
print(len(x)) # 6
5
string(字串)
 str() 進行型別轉換
x = 10
print(type(x)) # <class 'int'>
y = str(x)
print(type(y)) # <class 'str'>
6
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'
7
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
8
string(字串)_常用method
string.split(separator, maxsplit)
 separator:分割符號,預設值為空格
 maxsplit:分割次數;預設值為全部分割
字串切割並存成list
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']
9
string 串接
可透過 + 或空格串接字串
print("Hello" + " world")
print("Hello " "world")
# Hello world
那如果要串接數個字串或串接時要進行額外處理,改怎做呢?
我們可用兩種string format處理
 string.format
 f-string
10
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 11
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 12
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
13
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
print(x[-1: :-1]) # nohtyPolleH
print(x[::-1]) # nohtyPolleH
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
H e l l o P y t h o n
14
Slicing for 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
15
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']
16
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]
17
list 常用方法(method)
 用append在串列最後一元素接續新增單一物件
 list.append(element)
a = [] # 空串列
a.append(100)
print(a) # [100]
 大部分method會修改原串列(existing list)
 如用變數接收,結果會是None
b = a.append(100)
print(b) # None
18
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]
19
list 常用方法(method)
 用index查詢物件的位置
 list.index(element)
 用count計算指定物件在串列中出現的次數
 list.count(element)
a = ['a', 'b', 'c', 'd']
print(a.index('c'))
a = ['a', 'b', 'c', 'd', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
print(a.count('c'))
# 12
3? 有序資料index從0算起
實際結果
2
Why?
20
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]
21
list 常用方法(method)
用join把串列整併形成字串(string)
 ‘ ’.join(iterable); ‘’可放入元素間分隔符號
word_list = ['Hello', 'world']
word_str = ' '.join(word_list)
print(word_str) # Hello world
word_str2 = ' & '.join(word_list)
print(word_str2) # Hello & world
22
reverse vs 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] 23
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]
24
tuple
 有序資料但資料不可變
 用()建立
x = () # 空tuple
x = (1, 2, 3, 4)
 如何建立單一個元素的tuple
x = (1)
print(x) # 1 is a int type
我們直覺建立 正確:(元素, )
x = (1, )
print(x) # (1, )
25
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
26
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
27
dict
 查字典
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'
 {key1: value1, key2: value2, …}
 key  不可變的物件, 如str, number, tuple
 value  任意物件
 如使用tuple當key, 要確保每個元素都是不可變
28
dict
 key有重複,後值(value)取代前值
z = {'a':1, 'b':2, 'a':"python", 2:'abc', 'a':9999888}
print(z)
# {'a': 9999888, 'b': 2, 2: 'abc'}
 如何在原有dict新增key:value?
 dict[new_key] = value
z = {'a':1, 'b':2, 'a':"python", 2:'abc', 'a':9999888}
z["apple"] = 1094
print(z)
# {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094}
29
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) iterable  {key:value}
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} 30
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 31
在Python中大小寫有差(case sensitive),
執行時會被視為不同的變數
dict 常用方法(method)
 當我們想取用的key:value不在dict,不想出現KeyError,
且希望同步新增該組key:value,該怎做?
 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'}
32
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])])
33
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
 無index
 slicing不適用
 {} 是空字典; set()是空集合
 元素具唯一性
34
Recap
 索引值(index)從0算起
 有序資料可用Slicing
 string, tuple資料不可變
 set 元素具唯一性
35
if-else條件式
 if 條件式成立就執行程式碼,否則就執行else所屬的程式碼
if 條件式成立:
執行code
else:
執行code
if x >= 100:
print("數值大於等於100")
else:
print("數值小於100")
36
x = 100
# 數值大於等於100
if-else條件式
 elif 多種情況需判別
if 條件式成立:
執行code
elif 條件式成立:
執行code
else:
執行code
if age < 0:
print("年齡必須大於0")
elif age > 18:
print("你可以考駕照了")
else :
print("尚未到法定年齡")
37
age = 10
# 尚未到法定年齡
while loop
 條件式成立,執行所屬的程式碼,如否,跳出while迴圈
n = 1
nums = []
while n < 5:
nums.append(n)
n += 1
print(nums)
# [1, 2, 3, 4]
while 條件式成立:
執行code
38
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']
"12345"
num
39
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]
40
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]
41
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]
nums = []
for num in range(1, 10):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
nums = [num**2 for num in range(1, 10)]
print(nums)# [1, 4, 9, 16, 25, 36, 49, 64, 81]
42
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
43
有同樣功能該怎做…….?
 ctrl + c / ctrl + v
如有數個地方使用同功能,難道要一直複製貼上?
如這功能有調整,複製的地方全要同步手動調?
nums = []
for num in range(1, 10):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
nums = []
for num in range(1, 9):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8]
44
函式(function)
 整併重複使用&功能相同的程式碼
 組成:
 函式名:小寫, _ 連結兩個以上英文字
 參數
 block code
def function_name(parameter,..):
block code
print
function_name()
def function_name(parameter,..):
block code
return
result = function_name()
print(result) 45
有同樣功能該怎做…….?
 ctrl + c / ctrl + v  透過function改寫
nums = []
for num in range(1, 10):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]
nums = []
for num in range(1, 9):
nums.append(num)
print(nums)
#[1, 2, 3, 4, 5, 6, 7, 8]
def generate_list(n):
nums = []
for num in range(1,n):
nums.append(num)
print(nums)
generate_list(10)
generate_list(9)
46
函式(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)
#TypeError: add_value() missing 1 required positional argument: 'y' 47
函式(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
48
引數要如何傳遞到函式呢?
 利用參數位置進行傳遞
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
49
一個參數對應多個引數
 *args 接收位置參數, 形成tuple
**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 summation(*args):
print(args)
print(sum(args))
summation(1,2,3,4,5,6)
# (1, 2, 3, 4, 5, 6)
# 21
50
一個參數對應多個引數
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
51
實際案例
 假設餐廳提供三種餐點
 三明治, 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刷題鍛鍊班 52
class
 OOP(Object Oriented Programming)
程式碼可再利用(reuse)
易於維護與問題排除(debugging)
針對專案需求進行客製化。
 Python利用類別(class)實現OOP
53
class
 類別為物件的設計藍圖,同一個類別的物件會有相同的屬性與操作
方法(method)。
class Human:
pass
 屬性(Attribute):為類別會有的特徵。
Human
Attribute
Method
姓名, 年齡, 髮色, 身高, …….
走, 跳, 說話, ……..
 操作方式(Method):為類別操作的方式,期達到我們想要的結果。
class HumanBeing:
pass
54
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"
55
class
 屬性(Attribute):為類別會有的特徵。
 操作方式(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"
設定初始值
1.使用時機:每個實例物件皆有共同的屬性
2.在實例化過程中,初始值會自動建立
3.實例化給予的值不同,初始值結果會不同
56
實例化(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)
57
如何取用類別的屬性與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
58
如何取用類別的屬性與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 59
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)
60
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 61
inheritance
 Child class 如何取用 Parent class的方法(method)?
 super().method
 ParentClass.method
 明確知道取用哪個Parent Class
 缺乏彈性, 當Parent Class改名, 就要逐一修改
62
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
63
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 64
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.... 65
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.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' 66
交流時間
67

More Related Content

PDF
RとPythonによるデータ解析入門
PDF
クラスタリング
PPTX
Python入門:5大概念初心者必備 2021/11/18
PDF
Python元組,字典,集合
PDF
Python learn guide
PDF
PDF
PDF
Ch4 教學
RとPythonによるデータ解析入門
クラスタリング
Python入門:5大概念初心者必備 2021/11/18
Python元組,字典,集合
Python learn guide
Ch4 教學

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

PDF
Scilab introduction(Scilab 介紹)
PDF
Ch8 教學
PDF
PPTX
ncuma_串列.pptx
PPTX
Python 入門
PDF
Ppt 51-77
PDF
Ppt 51-77
PDF
PPT
第5章数组
PPT
C程式-陣列與指標
PDF
Python程式設計 - 串列資料應用
PDF
PDF
Ch9 教學
PDF
Python学习笔记
PDF
PDF
Ch11 教學
PDF
Ch10 習題
PPTX
ncuma_pylab.pptx
PDF
Arrays的Sort算法分析
PPTX
R intro 20140716-basic
Scilab introduction(Scilab 介紹)
Ch8 教學
ncuma_串列.pptx
Python 入門
Ppt 51-77
Ppt 51-77
第5章数组
C程式-陣列與指標
Python程式設計 - 串列資料應用
Ch9 教學
Python学习笔记
Ch11 教學
Ch10 習題
ncuma_pylab.pptx
Arrays的Sort算法分析
R intro 20140716-basic
Ad

Python入門:5大概念初心者必備

  • 3. Agenda 概念一:你需知道index, string, slicing 概念二:初探python資料結構 概念三:什麼是if-else, for , while 概念四: Code能重複用的函式 概念五:類別(class)是何物 3
  • 4. index(索引值)  在有序資料中,元素的順序。  有序資料:string, list, tuple  有序資料的index  從 0 開始算 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 4
  • 5. string(字串)  字元序列(Sequence)  字元有順序  資料不可變  如何建立string?  如何計算string長度? x = 'anx' y = "hsb" print(type(x), type(y)) # <class 'str'> <class 'str'> x = "123456" print(len(x)) # 6 5
  • 6. string(字串)  str() 進行型別轉換 x = 10 print(type(x)) # <class 'int'> y = str(x) print(type(y)) # <class 'str'> 6
  • 7. 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' 7
  • 8. 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 8
  • 9. string(字串)_常用method string.split(separator, maxsplit)  separator:分割符號,預設值為空格  maxsplit:分割次數;預設值為全部分割 字串切割並存成list 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'] 9
  • 10. string 串接 可透過 + 或空格串接字串 print("Hello" + " world") print("Hello " "world") # Hello world 那如果要串接數個字串或串接時要進行額外處理,改怎做呢? 我們可用兩種string format處理  string.format  f-string 10
  • 11. 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 11
  • 12. 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 12
  • 13. 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 13
  • 14. 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 print(x[-1: :-1]) # nohtyPolleH print(x[::-1]) # nohtyPolleH 0 1 2 3 4 5 6 7 8 9 10 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 H e l l o P y t h o n 14
  • 15. Slicing for 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 15
  • 16. 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'] 16
  • 17. 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] 17
  • 18. list 常用方法(method)  用append在串列最後一元素接續新增單一物件  list.append(element) a = [] # 空串列 a.append(100) print(a) # [100]  大部分method會修改原串列(existing list)  如用變數接收,結果會是None b = a.append(100) print(b) # None 18
  • 19. 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] 19
  • 20. list 常用方法(method)  用index查詢物件的位置  list.index(element)  用count計算指定物件在串列中出現的次數  list.count(element) a = ['a', 'b', 'c', 'd'] print(a.index('c')) a = ['a', 'b', 'c', 'd', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c'] print(a.count('c')) # 12 3? 有序資料index從0算起 實際結果 2 Why? 20
  • 21. 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] 21
  • 22. list 常用方法(method) 用join把串列整併形成字串(string)  ‘ ’.join(iterable); ‘’可放入元素間分隔符號 word_list = ['Hello', 'world'] word_str = ' '.join(word_list) print(word_str) # Hello world word_str2 = ' & '.join(word_list) print(word_str2) # Hello & world 22
  • 23. reverse vs 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] 23
  • 24. 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] 24
  • 25. tuple  有序資料但資料不可變  用()建立 x = () # 空tuple x = (1, 2, 3, 4)  如何建立單一個元素的tuple x = (1) print(x) # 1 is a int type 我們直覺建立 正確:(元素, ) x = (1, ) print(x) # (1, ) 25
  • 26. 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 26
  • 27. 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 27
  • 28. dict  查字典 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'  {key1: value1, key2: value2, …}  key  不可變的物件, 如str, number, tuple  value  任意物件  如使用tuple當key, 要確保每個元素都是不可變 28
  • 29. dict  key有重複,後值(value)取代前值 z = {'a':1, 'b':2, 'a':"python", 2:'abc', 'a':9999888} print(z) # {'a': 9999888, 'b': 2, 2: 'abc'}  如何在原有dict新增key:value?  dict[new_key] = value z = {'a':1, 'b':2, 'a':"python", 2:'abc', 'a':9999888} z["apple"] = 1094 print(z) # {'a': 9999888, 'b': 2, 2: 'abc', 'apple': 1094} 29
  • 30. 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) iterable  {key:value} 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} 30
  • 31. 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 31 在Python中大小寫有差(case sensitive), 執行時會被視為不同的變數
  • 32. dict 常用方法(method)  當我們想取用的key:value不在dict,不想出現KeyError, 且希望同步新增該組key:value,該怎做?  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'} 32
  • 33. 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])]) 33
  • 34. 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  無index  slicing不適用  {} 是空字典; set()是空集合  元素具唯一性 34
  • 35. Recap  索引值(index)從0算起  有序資料可用Slicing  string, tuple資料不可變  set 元素具唯一性 35
  • 36. if-else條件式  if 條件式成立就執行程式碼,否則就執行else所屬的程式碼 if 條件式成立: 執行code else: 執行code if x >= 100: print("數值大於等於100") else: print("數值小於100") 36 x = 100 # 數值大於等於100
  • 37. if-else條件式  elif 多種情況需判別 if 條件式成立: 執行code elif 條件式成立: 執行code else: 執行code if age < 0: print("年齡必須大於0") elif age > 18: print("你可以考駕照了") else : print("尚未到法定年齡") 37 age = 10 # 尚未到法定年齡
  • 38. while loop  條件式成立,執行所屬的程式碼,如否,跳出while迴圈 n = 1 nums = [] while n < 5: nums.append(n) n += 1 print(nums) # [1, 2, 3, 4] while 條件式成立: 執行code 38
  • 39. 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'] "12345" num 39
  • 40. 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] 40
  • 41. 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] 41
  • 42. 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] nums = [] for num in range(1, 10): nums.append(num) print(nums) #[1, 2, 3, 4, 5, 6, 7, 8, 9] nums = [num**2 for num in range(1, 10)] print(nums)# [1, 4, 9, 16, 25, 36, 49, 64, 81] 42
  • 43. 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 43
  • 44. 有同樣功能該怎做…….?  ctrl + c / ctrl + v 如有數個地方使用同功能,難道要一直複製貼上? 如這功能有調整,複製的地方全要同步手動調? nums = [] for num in range(1, 10): nums.append(num) print(nums) #[1, 2, 3, 4, 5, 6, 7, 8, 9] nums = [] for num in range(1, 9): nums.append(num) print(nums) #[1, 2, 3, 4, 5, 6, 7, 8] 44
  • 45. 函式(function)  整併重複使用&功能相同的程式碼  組成:  函式名:小寫, _ 連結兩個以上英文字  參數  block code def function_name(parameter,..): block code print function_name() def function_name(parameter,..): block code return result = function_name() print(result) 45
  • 46. 有同樣功能該怎做…….?  ctrl + c / ctrl + v  透過function改寫 nums = [] for num in range(1, 10): nums.append(num) print(nums) #[1, 2, 3, 4, 5, 6, 7, 8, 9] nums = [] for num in range(1, 9): nums.append(num) print(nums) #[1, 2, 3, 4, 5, 6, 7, 8] def generate_list(n): nums = [] for num in range(1,n): nums.append(num) print(nums) generate_list(10) generate_list(9) 46
  • 47. 函式(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) #TypeError: add_value() missing 1 required positional argument: 'y' 47
  • 48. 函式(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 48
  • 49. 引數要如何傳遞到函式呢?  利用參數位置進行傳遞 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 49
  • 50. 一個參數對應多個引數  *args 接收位置參數, 形成tuple **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 summation(*args): print(args) print(sum(args)) summation(1,2,3,4,5,6) # (1, 2, 3, 4, 5, 6) # 21 50
  • 51. 一個參數對應多個引數 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 51
  • 52. 實際案例  假設餐廳提供三種餐點  三明治, 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刷題鍛鍊班 52
  • 53. class  OOP(Object Oriented Programming) 程式碼可再利用(reuse) 易於維護與問題排除(debugging) 針對專案需求進行客製化。  Python利用類別(class)實現OOP 53
  • 54. class  類別為物件的設計藍圖,同一個類別的物件會有相同的屬性與操作 方法(method)。 class Human: pass  屬性(Attribute):為類別會有的特徵。 Human Attribute Method 姓名, 年齡, 髮色, 身高, ……. 走, 跳, 說話, ……..  操作方式(Method):為類別操作的方式,期達到我們想要的結果。 class HumanBeing: pass 54
  • 55. 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" 55
  • 56. class  屬性(Attribute):為類別會有的特徵。  操作方式(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" 設定初始值 1.使用時機:每個實例物件皆有共同的屬性 2.在實例化過程中,初始值會自動建立 3.實例化給予的值不同,初始值結果會不同 56
  • 57. 實例化(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) 57
  • 58. 如何取用類別的屬性與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 58
  • 59. 如何取用類別的屬性與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 59
  • 60. 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) 60
  • 61. 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 61
  • 62. inheritance  Child class 如何取用 Parent class的方法(method)?  super().method  ParentClass.method  明確知道取用哪個Parent Class  缺乏彈性, 當Parent Class改名, 就要逐一修改 62
  • 63. 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 63
  • 64. 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 64
  • 65. 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.... 65
  • 66. 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.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' 66