網上有這樣一個段子,在評論語言好壞的時候,都會有人評論說PHP是世界上最好的語言,人生苦短我用Python,這里姑且不去評論語言的好壞,每一個語言存在都有它的價值,譬如C語言適合底層開發,整個Linux操作系統幾乎都是用C語言開發的,而像Go語言適合高並發的網絡開發一樣,並不是說像Go干不了其它事情,只是更適合某種應用場景。
談到python之美,我認為這里有兩個流派:python和pythonic。在我理解,Pythonic 就是很Python的Python代碼,也就是用非常優美的python代碼實現功能。舉例說明:
我們要打開文件進行處理,在處理文件過程中可能會出錯,但是,我們需要在處理文件出錯的情況下,也順利關閉文件。
傳統風格的Python代碼:
1 file= open(C:\data.txt') 2 try: for line in file: 3 ...... 4 finally: 5 file.close()
Pythonic的代碼:
1 with open(c:\data.txt') as file: 2 for line in file: 3 ......
通過with上下文管理,無需考慮資源釋放問題以及異常情況下的資源釋放問題,上下文管理器會幫你去處理。
再舉一個例子:
字符串鏈接
1 names = ['1', '2', '3', '4', '5', '6', '7', '8'] 2 s = names[0] for name in names[1:]: 3 s += ', ' + name print(s)
pythonic
1 print(', '.join(names))
可見pythonic的代碼是如此的簡潔和優雅。
具體更多的pythonic的代碼,大家可以參考相關書籍,平時在學習和工作中注意積累。關於pythonic,這里不得不來一段python之禪,在python控制台下,輸入:
import this
會顯示下面內容:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
中文意思如下:
Python之禪 by Tim Peters
優美勝於丑陋
明了勝於晦澀
簡潔勝於復雜
復雜勝於凌亂
扁平勝於嵌套
間隔勝於緊湊
可讀性很重要
即便假借特例的實用性之名,也不可違背這些規則
不要包容所有錯誤,除非你確定需要這樣做
當存在多種可能,不要嘗試去猜測
而是盡量找一種,最好是唯一一種明顯的解決方案
雖然開始這並不容易,因為你不是Python之父
做也許好過不做,但不假思索就動手還不如不做
如果你無法向人描述你的方案,那肯定不是一個好方案;反之亦然
命名空間是一種絕妙的理念,我們應當多加利用