《Pytho Crash Course》(PCC)和《Learn Python The Hard Way》(LPTHW)都提到了編程的風(fēng)格問題捂蕴。這里把這些討論的內(nèi)容總結(jié)一下媒殉。
對齊和空格
- 由于Python實際上已經(jīng)默認(rèn)必須對齊和空格才能運(yùn)行鬓椭,所以這個問題不大;
- 大多數(shù)編輯器欢峰,包括Pycharm, geany等在回車時都已按照Python格式自動對齊梨树;
- Python的官網(wǎng)提供了一些示例坑夯,很值得反復(fù)翻閱。
命名格式
最常見的有兩種命名格式抡四,一種叫做camel case或駝峰命名法柜蜈,比如SuperGoldFactory,另外一種叫underscore case即下劃線命名法指巡,比如super_gold_factory淑履。Python一般采用駝峰命名法。詳見PCC9.6節(jié)和LPTHW的EX45藻雪。以及stackexchange的討論秘噪。
注釋
LPTHW提到,注釋最好解釋why而不是what勉耀,因為程序代碼已經(jīng)交代了what/how: "When you write comments, describe why you are doing what you are doing. The code already says how, but why you did things the way you did is more important."
函數(shù)取名
LPTHW的EX45提到指煎,建議用命令動作給函數(shù)取名,而非用概括功能用詞給函數(shù)取名便斥。"instead of nameing your functions after what the function does, name it as if it's a command you are giving to the class."