shanchen
shanchen

hi

Functional Programming in Python筆記 Part 2: Callables

主要講python如何create跟call functions

  1. Named Functions and Lambdas
    主要講lambda跟一般function
  2. Closures and Callable Instances
    A class is “data with operations attached” while a closure is “operations with data attached.

class vs closure

小心要closure裡面變數的binding.

3. Methods of Classes- Accessors and Operators
 講@property以及雙底線方法的調整
(可以看這篇了解底線到底在幹嘛Understanding the underscore( _ ) of Python)

3. Methods of Classes- Static Methods of Instances
 講static method, 一堆pure function就不要call instance了

3. Methods of Classes-Generator Functions
 用yield當作function回傳,傳回一個iterator, 下一章講更詳細

4. Pattern Matching
 講如果要寫一個剪刀石頭布程式,要如何設計比較好。
這邊列了四種寫法 Many Branches, Delegating to Objects, Pattern Matching
 和predicate-based Dispatch

基本定義

  • Many Branches
    定義 beat2 function 然後判斷都寫在裡面
  • Delegating to Objects
    在每種object裡定義beat function, 然後call
  • Pattern Matching
    用pattern方式 定義beat, code比較漂亮
  • Predicate-based Dispatch
    作者自己幻想的library,可以寫得很漂亮。但目前沒有好的

因為順便可以複習scala, 寫了盡量接近Delegating to Objects和Pattern Matching的版本 https://github.com/hsuanchenli/RPS_Game.git
Scala的pattern matching本來就有,可以寫得很簡潔。

最近在Akka看到的good practice, 將case class或case object包在跟class 同名的object, 可以很好的表達只放資料的class的type。這樣就可以在method中用來比對不同type class做出相對應的事情。

覺得一般在python, 應該用Delegating to Objects來做比較直覺,用Pattern Matching方法的話,除非同事也都這樣寫,不然風格差很多=.=

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论