內容 / 重點 / 注意事項 / 其他或補充

sample code https://github.com/arthas989/python2022

118. First Class Objects

119. Decorators

120. Generator

121. Iteration, Iterable, and Iterator

122. Stdin, Stdout, Pipe

Chapter 9 - Advanced Functions
118. First Class Objects 複習講座60 higher-order function
是說一個function拿其他function做為他的argument
EX:map function (object)
map(Func, Iterable)
filter(Func, Iterable)
看上面

python的function是First Class Object,是說可以把python的function看做是object或variable 所以function可以做到下面的事: 1.被指派為變數 (變臉) 2.被當成argument傳入其他function g(f(x)) 3.被其他function回傳 4.放進list,tuple,dictionary

JavaScript、Python、Go是First Class Object Java、C++是Second Class Object 上面4點特性不適用

補充 第一類對象(First-class Object)在1960年由 Christopher Strachey 發明,原來稱之為第一類公民(First-class citizen),意思是然函數可以作為電腦中的第一類公民。英文中也稱之為First-class entity或First-class value。

In programming language design, a first-class citizen (also object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as a parameter, returned from a function, and assigned to a variable.

第一類對象不一定是指OOP中的對象,而是指程序中的所有實體,比如:變數、函數、陣列和字典等等。第一類對象擁有以下特徵:

可以被存入變數或其他結構 可以作為參數傳遞給其他方法/函數 可以作為方法/函數的返回值 可以在執行期(runtine)被創建,無需在設計期全部寫出 有固定身份

https://ithelp.ithome.com.tw/articles/10222472

https://medium.com/ryanjang-devnotes/who-is-first-class-citizen-in-programming-world-b92c67b32635 | | 119. Decorators | Decorators:裝飾器 之前講到的@property 虛擬屬性也是一個decorator

| | 120. Generator | 複習 generator(Chapter3-Control Flow 講座51 6:09 ) 了解yeild、yeild from | | 121. Iteration, Iterable, and Iterator | for loop的原理 重點:把一個object做成 iterable,iterator 就能放入for loop 第一種做法: iterable ⇒ (1) __iter__ method returns an iterator any generator都是iterator

第二種做法:

iterable => (2) implements __getitem__()

| | 122. Stdin, Stdout, Pipe | Pipe是什麼? 在終端機或命令列中執行python的程式碼 常會用到stdin及stdout,以及pipe pipe是stdout再導向到另一個stdin的管道

import sys sys.argv

寫入 overwrite

附加 append

< 讀入 read

http://122-1.py 範例說明: 有一個文字檔122_infile.txt 有一個122-1.py檔,要讀入infile文字檔 透過處理(把zero換成數字0) 產生新的文字檔122_outfile.txt

CMD要執行 python 122-1.py zero 0 < 122_infile.txt >122_outfile.txt 參數要不要先輸入?要

再來要示範pipe | 用法 執行122-1.py檔讀入文字檔122_infile.txt 要把0換成zero,透過 | 再重導至原程式 把1換成one,最後輸出至122_outfile.txt

CMD要執行 python 122-1.py 0 zero < 122_infile.txt | 122-1.py 1 one > 122_outfile.txt 第一次寫錯了,outfile變成空的了,而且導向要用什麼程式開檔 再修正 python 122-1.py 0 zero < 122_infile.txt | python 122-1.py 1 one > 122_outfile.txt

pipe是來自unix system 上面的程式可以直接寫完替換0跟1的功能 但在unix的設計理念就是一個program只需要做一件事 再把每個小program組合起來 (較有彈性、擴充性與變化) |