13.Python 裝飾器 (Decorator)
使用裝飾器可以幫助你避免代碼的重複,從而提高了代碼的重用性和可擴展性。
甲居工作室日期:2024/04/10
想必大家上一章節頭腦都快要炸裂了吧?
本章談論輕鬆一點的事情。
在 Python 有個小小的彩蛋,只要使用者import this就會顯示下列內容:
>>> import thisThe Zen of Python, by Tim PetersBeautiful 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 之父)
做優於不做。
然而不假思索還不如不做。
很難解釋的,必然是壞方法。
很好解釋的,可能是好方法。
命名空間是個絕妙的主意,我們應好好利用它。
建議大家訂出自己或是團隊的轉寫風格對於未來會有幫助的。
這邊提供作者採用的準則部分內容供大家參考
4.若程式意義不易了解,應加註解說明
5.function, class 前後各空 3 行,程式中為分隔區塊,可空1行