1. 程式人生 > >Python 設計模式之禪

Python 設計模式之禪

在Python 終端會話中執行命令import this。

>>> 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程式設計師篤信程式碼可以編寫得漂亮而優雅。程式設計是要解決問題的,設計良好、高效而漂
亮的解決方案都會讓程式設計師心生敬意。隨著你對Python的認識越來越深入,並使用它來編寫越來
越多的程式碼,有一天也許會有人站在你後面驚呼:“哇,程式碼編寫得真是漂亮!”

如果有兩個解決方案,一個簡單,一個複雜,但都行之有效,就選擇簡單的解決方案吧。這
樣,你編寫的程式碼將更容易維護,你或他人以後改進這些程式碼時也會更容易。

現實是複雜的,有時候可能沒有簡單的解決方案。在這種情況下,就選擇最簡單可行的解決
方案吧。

即便是複雜的程式碼,也要讓它易於理解。開發的專案涉及複雜程式碼時,一定要為這些程式碼編
寫有益的註釋。

如果讓兩名Python程式設計師去解決同一個問題,他們提供的解決方案應大致相同。這並不是說
程式設計沒有創意空間,而是恰恰相反!然而,大部分程式設計工作都是使用常見解決方案來解決簡單的
小問題,但這些小問題都包含在更龐大、更有創意空間的專案中。在你的程式中,各種具體細節
對其他Python程式設計師來說都應易於理解。

你可以將餘生都用來學習Python和程式設計的紛繁難懂之處,但這樣你什麼專案都完不成。不要
企圖編寫完美無缺的程式碼;先編寫行之有效的程式碼,再決定是對其做進一步改進,還是轉而去編
寫新程式碼。