一、Python 用下划线作为变量前缀和后缀指定特殊变量
1. 单下划线开头:
_xxx:弱“内部使用”标识,如:”from Module import *”,将不导入所有以下划线开头的对象,包括包、模块、成员
2. 双下划线开头:
__xxx:模块内的私有成员,外部无法直接调用。
即:私有类型的变量。只能是允许这个类本身进行访问了。连子类也不可以
3. 双下划线开头和结尾:
__xxx__ :系统定义名字, 用户无法控制的命名空间中的“魔术”对象或属性, 如:
__name__、__doc__、__init__、__import__、__file__等;
二、python常用的魔法方法及变量
转自:http://www.cnblogs.com/DxSoft/p/3506627.html
__new__: 是一个类的初始化过程中第一个被执行的方法。它创建了类,然后把一些参数传递给__init__
_init__(self, [...): 类的构造器,当初始构造方法被执行
__del__(self):如果 __new__ 和 __init__ 形成一个类的构造函数,__del__ 是就是析构函数
__str__(self):定义当 str() 被你的一个类的实例调用时所要产生的行为。
Magic
Method
何时被调用(例子)
Explanation
__new__(cls [,...])
instance = MyClass(arg1, arg2)
__new__ is called on instance creation
__init__(self [,...])
instance = MyClass(arg1, arg2)
__init__ is called on instance creation
__cmp__(self, other)
self == other, self > other, etc.
Called for any comparison
__pos__(self)
+self
Unary plus sign
__neg__(self)
-self
Una