新手覺得簡單,但其實這玩意不比C簡單。有哪些區分新手和老手的知識,習慣和細節呢?謝謝!
回複內容:
前人問過了:
Hidden features of Python
摘抄目錄:
- Argument Unpacking
- Braces
- Chaining Comparison Operators
- Decorators
- Default Argument Gotchas / Dangers of Mutable Default arguments
- Descriptors
- Dictionary default .get value
- Docstring Tests
- Ellipsis Slicing Syntax
- Enumeration
- For/else
- Function as iter() argument
- Generator expressions
- import this
- In Place Value Swapping
- List stepping
- __missing__ items
- Multi-line Regex
- Named string formatting
- Nested list/generator comprehensions
- New types at runtime
- .pth files
- ROT13 Encoding
- Regex Debugging
- Sending to Generators
- Tab Completion in Interactive Interpreter
- Ternary Expression
- try/except/else
- Unpacking+print() function
- with statement
另外還有一個是黑魔法元類:
譯文:http://blog.jobbole.com/21351/
原文:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
瞭解內建的幾大容器list/dict/set用什麼資料結構實現,以及一些基本操作的時間複雜度。這個不難,python的list實際上就是個vector,不是linked list,dict/set就是hash table。。然後避免犯頻繁在list中間插入/刪除之類的錯誤
這也使得python不適合函數式編程,像什麼lambda不能跨行都是小事,但是標準庫裡連持久化的列表/搜尋樹都沒有。。自己實現也不是不行,CPython函數調用開銷又大。
所以還是老老實實寫迴圈、拋異常吧,When in Rome, do as the Romans do。列幾個關鍵字吧:
decorator
yield(generator)
descriptor
method & function
slot
MRO
自省(id、type、dir、vars等等)
然後就是各種常用的模組吧,itertools、functools、collections、copy等吧
最後有興趣的話可以讀一下陳儒寫的《Python源碼剖析》,可以瞭解到小整數緩衝,int、list、dict緩衝池,字串intern機制,記憶體管理等內部實現。某個主要分支的某個小版本被牆了迭代器,產生器,可迭代對象。搞清楚這幾個概念,面試官就會覺得你很牛逼了。正負數除法求商和餘數的值我覺得最有趣的莫過於Method Resolution Order(MRO)。
MRO是指class inheritance中method或者attribute的search order。最簡單的情況是classic class的 inheritance tree。這時候,search order是depth first, from left to right。
舉個例子:
class A():
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
在上面的inheritance tree中,class D的MRO應該是 D,B,A,C。值得注意的是,A的位置在C的前面。
對於new style class, python 2.2和2.3(或以上)也有區別,2.3以後的MRO algorithm叫C3 algorithm。具體的細節大家可以google一下,個人覺得非常有趣。你可以學完基礎Python的文法之後學一下其他語言,看看他們的一些特徵能不能在Python中實現。
我舉個小例子。
在Racket裡面,有一個stream的構造。
(define ones (lambda () (cons 1 ones)))
一個非常重要的內建函數: type 。Talks | Armin Ronacher's Thoughts and Writings
這裡的pdf中有, 我截一段你看下
或者這個網頁A Curious Course on Coroutines and Concurrency
應該是將Python的yield用得超好了
舉例: