python中的下划线及双下划线

一、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 Unary minus sign
__invert__(self) ~self Bitwise inversion
__index__(self) x[self] Conversion when object is used as index
__nonzero__(self) bool(self) Boolean value of the object
__getattr__(self, name) self.name # name doesn‘t exist Accessing nonexistent attribute
__setattr__(self, name, val) self.name = val Assigning to an attribute
__delattr__(self, name) del self.name Deleting an attribute
__getattribute__(self, name) self.name Accessing any attribute
__getitem__(self, key) self[key] Accessing an item using an index
__setitem__(self, key, val) self[key] = val Assigning to an item using an index
__delitem__(self, key) del self[key] Deleting an item using an index
__iter__(self) for x in self Iteration
__contains__(self, value) value in self,value not in self Membership tests using in
__call__(self [,...]) self(args) "Calling" an instance
__enter__(self) with self as x: with statement context managers
__exit__(self, exc, val, trace) with self as x: with statement context managers
__getstate__(self) pickle.dump(pkl_file, self) Pickling
__setstate__(self) data = pickle.load(pkl_file) Pickling

 

三、 双下划线开头和结尾的函数及变量枚举: 

x.__add__(y)          等价于  x+y
x.__contains__(y)   等价于 y in x, 在list,str, dict,set等容器中有这个函数
__base__, __bases__, __mro__,    关于类继承和函数查找路径的
class.__subclasses__(),                 返回子类列表
x.__call__(...) 等价于   x(...)
x.__cmp__(y) 等价于   cmp(x,y)
x.__getattribute__(‘name‘) 等价于  x.name   等价于  getattr(x, ‘name‘),  比__getattr__更早调用
x.__hash__()  等价于   hash(x)
x.__sizeof__(), x在内存中的字节数, x为class得话, 就应该是x.__basicsize__
x.__delattr__(‘name‘) 等价于 del x.name
__dictoffset__ attribute tells you the offset to where you find the pointer to the __dict__ object in any instance object that has one. It is in bytes.
__flags__, 返回一串数字,用来判断该类型能否被序列化(if it‘s a heap type), __flags__ & 512
S.__format__, 有些类有用
x.__getitem__(y) == x[y], 相应还有__setitem__, 某些不可修改类型如set,str没有__setitem__
x.__getslice__(i, j) == x[i:j], 有个疑问,x=‘123456789‘, x[::2],是咋实现得
__subclasscheck__(), check if a class is subclass
__instancecheck__(), check if an object is an instance
__itemsize__, These fields allow calculating the size in bytes of instances of the type. 0是可变长度, 非0则是固定长度
x.__mod__(y) == x%y, x.__rmod__(y) == y%x
x.__module__ , x所属模块
x.__mul__(y) == x*y,  x.__rmul__(y) == y*x

__reduce__, __reduce_ex__ , for pickle

__slots__ 使用之后类变成静态一样,没有了__dict__, 实例也不可新添加属性

__getattr__ 在一般的查找属性查找不到之后会调用此函数

__setattr__ 取代一般的赋值操作,如果有此函数会调用此函数, 如想调用正常赋值途径用 object.__setattr__(self, name, value)

__delattr__ 同__setattr__, 在del obj.name有意义时会调用

 

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 Unary minus sign
__invert__(self) ~self Bitwise inversion
__index__(self) x[self] Conversion when object is used as index
__nonzero__(self) bool(self) Boolean value of the object
__getattr__(self, name) self.name # name doesn‘t exist Accessing nonexistent attribute
__setattr__(self, name, val) self.name = val Assigning to an attribute
__delattr__(self, name) del self.name Deleting an attribute
__getattribute__(self, name) self.name Accessing any attribute
__getitem__(self, key) self[key] Accessing an item using an index
__setitem__(self, key, val) self[key] = val Assigning to an item using an index
__delitem__(self, key) del self[key] Deleting an item using an index
__iter__(self) for x in self Iteration
__contains__(self, value) value in self,value not in self Membership tests using in
__call__(self [,...]) self(args) "Calling" an instance
__enter__(self) with self as x: with statement context managers
__exit__(self, exc, val, trace) with self as x: with statement context managers
__getstate__(self) pickle.dump(pkl_file, self) Pickling
__setstate__(self) data = pickle.load(pkl_file) Pickling

python中的下划线及双下划线,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。