Python 程式的資料結構 -  list (從變數到物件)


8/22/2020 Taiwan Python 讀書會


Ming-der Wang, 王銘德

(適合 Python 初學者)

for beginners only

環境設定

(直接跳到 3.x 不再用 python 2)

 

python 3.8.x

pip 20.1.x

 

自己電腦安裝

python -V

pip -V

 

python3 -V

pip3 -V

 

pytest

 

(利用 vi, vim 編輯器) (window 安裝 git for windows)

或用 Visual Studio Code

線上共筆

https://repl.it/

內含 git 版控

變數

 Python 的變數, 跟 C 變數不同

Python 語言                   記憶體             C 語言的記憶體

變數名稱 = 物件實體或含運算

aList = []
a = 100
aString = 'Hello World'
Pi = 3.1415926535897
aDog = Dog("小黃")
b = a * 3

舉例:

變數名稱

物件實體 (instance)

這裡的"等號" = , 表示右邊的物件實體或經過運算後放入左邊的變數

(嚴格說, 應該左邊變數名稱指向右邊的結果記憶體位置)

變數名稱命名有以下限制

  • 要以英文字母當開頭, A-z, 或底線 _
  • 不能用數字當開頭
  • 符號不能用 !@#$%^&* 等
  •  
  • 不要用 33 個 Python3 的保留字 (例如 if)
  • 也不要用內建物件或 Fun (例如 list, len())
  • 也不要用系統常用的變數 (例如 __main__)
  •  
  • (中文很像也可以, function 命名不可以)
  • 用底線 _ 開頭的變數名稱, 有不公開的含義

Python 裡什麼都是物件

物件 (簡體中文叫: 对象)

 

物件的實體

*資料型態 class ( => type) 是哪一個類別

* 內容 values ( => attributes) 屬性

* 運算元 functions ( => methods) 函式方法

(Object) 物件

attributes (屬性)

methods (functions) (運算)

 

(類別) Class 定義了 Object,而 Object 就是 Class 的一個 Instance (實體)

沒用 Class 

student_name = '李大中'

ch_score = 98

math_score = 90

 

# 計算總分和平均

total = ch_score + math_score

average = total / 2

def avg:

    return total/2

 

print('平均成績:', avg())

用物件表示

class Student:

  def __init__(self,name,ch_score, math_score): 

    self.name = name

    self.ch_score = ch_score

    self.math_score = math_score

  def average(self):

    return (self.ch_score + self.math_score) / 2

 

student_lee = Student('李大中', 98, 90)

 

 

print ( '平均成績:', student_lee.average() )

Class 名稱第一個字用大寫字母

self 是物件自己

物件實體 (instance)

Student 物件    

attributes (屬性)

methods (functions) (方法, 運算)

 

(類別) Class 定義了 Object,而 Object 就是 Class 的一個 Instance (實體)

student_lee

(可以再產生更多實體)

1. __init__ (實體創建時會被 call)

2. average

class Student:

哪些是 attributes 呢?

(有 3 個)

list 物件    

attributes (屬性)

methods (functions) (方法, 運算)

 

(類別) Class 定義了 Object,而 Object 就是 Class 的一個 Instance (實體)

aList = [1,2,3]

(可以再產生更多實體)

print(dir(list)) 非 _ 開頭的

'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'

print(type(list))<class 'list'>

哪些是 attributes 呢?

用 import inspect 找

普通 lists (陣列)

emptyList = [ ]

number_list = [1,2,3]

str_list = ['apple', 'orange']

 

一個物件的list

a_list = []

# 以下兩個是 Student 實體

student_lee = Student('李大中', 98, 90)

ming = Student('王銘德', 58, 62)

# list 可以用 append() 增加清單內容

a_list.append (student_lee)

a_list.append (ming)

# a_list[0] 表示第一個 物件的實體

print (a_list[0].name, a_list[0].average(), sep = ' ')

# for xxx in yyy, 可以重複跑完所有清單項目

for item in a_list:

  print (item.name, item.average(), sep = ' ')

# 先創建一個空的 list 叫 a_list

李大中 94.0
王銘德 60.0

李大中 94.0

物件跟 list 很重要

請多加練習

https://repl.it/ (有簡單的 git)

只要你有 github.com 帳號, 不必學 git 指令也能用

Python 程式的資料結構 -  list (從變數到物件)

By Ming-der Wang

Python 程式的資料結構 -  list (從變數到物件)

  • 1,008