变量命名,除了字符为[0-9,A-Z,a-z,_]及不用关键字作变量之外,模块名小写外,还有以下被Python遵循的惯例。
-
_通过交互式模式运行时,会保留最后的结果
>>> for _ in range(5):
... print(_)
...
0
1
2
3
4
>>> _
4
>>>
备注: 使用"_"在for循环中经常使用,避免遍历的最后一个结果,影响其他变量
-
_X不会被from module import * 导入
# FileName: var.py
_X = 100
PI = 3.14
D:\>python
Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from var import *
>>> print(PI)
3.14
>>> print(_X)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_X' is not defined
>>>
-
__X为类的本地变量
-
__X__是系统定义的变量名,对解释器有特殊的意义
>>> import math
>>> filter(lambda x: x.startswith("__"), dir(math))
['__doc__', '__name__', '__package__']
>>> print(math.__name__)
math
>>> print(math.__doc__)
This module is always available. It provides access to the
mathematical functions defined by the C standard.
>>>