《Pytho Crash Course》(PCC)和《Learn Python The Hard Way》(LPTHW)都提到了编程的风格问题。这里把这些讨论的内容总结一下。
对齐和空格
- 由于Python实际上已经默认必须对齐和空格才能运行,所以这个问题不大;
- 大多数编辑器,包括Pycharm, geany等在回车时都已按照Python格式自动对齐;
- Python的官网提供了一些示例,很值得反复翻阅。
命名格式
最常见的有两种命名格式,一种叫做camel case或驼峰命名法,比如SuperGoldFactory,另外一种叫underscore case即下划线命名法,比如super_gold_factory。Python一般采用驼峰命名法。详见PCC9.6节和LPTHW的EX45。以及stackexchange的讨论。
注释
LPTHW提到,注释最好解释why而不是what,因为程序代码已经交代了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."
函数取名
LPTHW的EX45提到,建议用命令动作给函数取名,而非用概括功能用词给函数取名。"instead of nameing your functions after what the function does, name it as if it's a command you are giving to the class."