目录

PEP8命名规范

Todo

  • Class Name中一段的翻译;

总则 Overriding Principle

API公开给使用者部分的命名应当能明确地反映出其用途。

命名方式简述 Descriptive: Naming Styles

常见命名方法如下:

  • 单个小写字母,如b
  • 单个大写字母,如B
  • 小写单词,如lowercase
  • 以下划线分隔的小写单词,如lower_case_with_underscores
  • 大写单词,如UPPERCASE
  • 以下划线分隔的大写单词,如UPPER_CASE_WITH_UNDERSCORES
  • 驼峰命名法,若有缩写名词则全字母大写,如CapitalizedWords
  • 首字母小写的驼峰,如mixedCase
  • 用下划线分隔单词的驼峰(巨丑,不推荐)。

Python中使用的四种特殊命名形式:

  • _single_leading_underscore以单下划线开头表示只供内部使用;
  • single_trailing_underscore_以单下划线结尾用于避免和Python关键字冲突;
  • __double_leading_underscore以双下划线开头会在类内部被改变名字来避免被外部使用;
  • __double_leading_and_trailing_underscore__以双下划线开头和结尾表示特殊对象或者属性,不要尝试自创这样的变量。

Python命名法 Prescriptive: Naming Conventions

避免使用的名字 Names to Avoid

小写的l(klm),大写的O(nop),大写的I(hij),不要把这三个字母用作单字母变量,会和数字01傻傻分不清楚~

包和模块的命名 Package and Module Names

  • 模块名应当使用全小写字母,并且越短越好必要时可以使用下划线来增强可读性
  • 包名也应当使用全小写字母,并且越短越好。但是不能使用下划线

用C/C++写的Python模块以单下划线开头?(存疑)

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket)。

类名 Class Names

类名应该使用驼峰命名法

这段不会翻译:

The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.

注意:类内部属性等的名字大多是一两个单词,命名方式与类名不同,后面会提到。只有两个例外——内建异常名和内建常量使用驼峰命名法

异常命名 Exception Names

异常的类型是class,所以遵循class的命名规则,使用驼峰命名法。另外,如果你定义的异常实际上是一个error,命名时要加Error的后缀。

全局变量命名 Global Variable Names

(我们希望全局变量是只用在一个模块中的全局变量)。全局变量的命名与函数命名相同(以下划线分隔的小写单词)?(存疑)

(Let’s hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

模块如果被设计成由from M import *的方式来被导入,并且全局变量是不公开的话,那么应当使用__all__来阻止暴露全局变量;或者使用老的加前缀命名方式,例如下划线前缀。

函数命名 Function Names

函数命名应当是全小写字母以下划线分隔单词以提高可读性。

首字母小写的驼峰命名法仅适用于已经成为主流的模块中的内容,例如threading.py,以保证向下的兼容性。

函数和方法的参数 Function and method arguments

实例方法的第一个参数永远是self,类方法的第一个参数永远是cls

如果一个函数的参数名与Python关键字冲突,那么最好在参数名后缀单下划线,而不是使用缩写或者错误的拼写。举个栗子,class_要比clss好。当然最好的方式是使用同义词来避免这样的冲突。

方法名和实例变量 Method Names and Instance Variables

使用函数命名规则:即使用全小写字母以下划线分隔单词以提高可读性。

不公开的方法和实例变量名称应该以单下划线开头

下面几段看不太懂:

To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules.

Python mangles these names with the class name: if class Foo has an attribute named __a , it cannot be accessed by Foo.__a . (An insistent user could still gain access by calling Foo._Foo__a .) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

Note: there is some controversy about the use of __names (see below).

常量名 Constants

以下划线分隔的全大写单词

参考链接