一.说明
因为python语言的不断变化,所以下面总结的内容在python的某一个版本中可能不适用,具体以python官网文档为准。
二._xxx单下划线开头
官方文档说明:
_single_leading_underscore:
weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
(1)翻译:这是一种提示,提示程序员这是供“内部使用”的,例如:不能通过“from module import *”导入。
(2)对于变量:无影响。
(3)对于函数:该函数不能通过“from module import *”导入,但是可以通过常规的的方式导入。
示例代码见参考资料。
三.xxx_单下划线结尾
官方文档说明:
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
(1)翻译:为了避免和Python关键字冲突。
(2)对于变量:为了避免和Python关键字冲突,无影响。
(3)对于函数:为了避免和Python关键字冲突,无影响。
示例代码见参考资料。
四.__xxx双下划线开头(注意是双下划线,虽然看起来像一条线)
官方说明:
_double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes_FooBar__boo; ).
(1)翻译:在命名类属性时,执行命名修饰(例如在类FooBar类,变量__boo 名字会修饰为_FooBar__boo)。——这样做一定程度上把变量/函数变成了私有的。
(2)变量:名字会被python解释器修改。
(3)函数:名字会被python解释器修改。
示例代码见参考资料。
五.__xxx__双下划线开头和双下划线结尾
官方说明:
_double_leading_and_trailing_underscore__:
"magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.
(1)翻译:在用户控制的的命名空间内存在的“魔力”对象或者属性,例如__init__, __import__ or __file__,不要创建这样的名字,只是使用python开发文档中提到的这类名字就可以了。
(2)变量:python定义的特殊变量,和正常的变量一样访问即可,不要自己创建。
(3)函数:python定义特殊方法,和正常的函数一样访问即可,不要自己创建。