_xxx 不能用’from module import *’导入
__xxx__ 系统定义名字
__xxx 类中的私有变量名
核心风格避免用下划线作为变量名的开始。
因为下划线对解释器有特殊的意义而且是内建标识符所使用的符号我们建议程序员避免用下划线作为变量名的开始。一般来讲变量名_xxx被看作是“私有 的”在模块或类外不可以使用。当变量是私有的时候用_xxx 来表示变量是很好的习惯。因为变量名__xxx__对Python 来说有特殊含义对于普通的变量应当避免这种命名风格。
“单下划线” 开始的成员变量叫做保护变量意思是只有类对象和子类对象自己能访问到这些变量
“双下划线” 开始的是私有成员意思是只有类对象自己能访问连子类对象也不能访问到这个数据。
以单下划线开头_foo的代表不能直接访问的类属性需通过类提供的接口进行访问不能用“from xxx import *”而导入以双下划线开头的__foo代表类的私有成员以双下划线开头和结尾的__foo__代表python里特殊方法专用的标识如 __init__代表类的构造函数。
现在我们来总结下所有的系统定义属性和方法 先来看下保留属性
序号
目的
所编写代码
Python 实际调用
①
初始化一个实例
<code>x = MyClass()</code>
<a href="http://docs.python.org/3.1/reference/datamodel.html#object.__init__" target="_blank">x.__init__()</a>
②
字符串的“官方”表现形式
<code>repr(x)</code>
<a href="http://docs.python.org/3.1/reference/datamodel.html#object.__repr__" target="_blank">x.__repr__()</a>
③
字符串的“非正式”值
<a href="http://docs.python.org/3.1/reference/datamodel.html#object.__str__" target="_blank">str(x)</a>
<code>x.__str__()</code>
④
字节数组的“非正式”值
<code>bytes(x)</code>
<code>x.__bytes__()</code>
⑤
格式化字符串的值
<code>format(x, format_spec)</code>
<a href="http://docs.python.org/3.1/reference/datamodel.html#object.__format__" target="_blank">x.__format__(format_spec)</a>
按照约定 <code>__repr__()</code> 方法所返回的字符串为合法的 Python 表达式。
在调用 <code>print(x)</code> 的同时也调用了 <code>__str__()</code> 方法。
由于 <code>bytes</code> 类型的引入而从 Python 3 开始出现。
遍历某个序列
<code>iter(seq)</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__iter__" target="_blank">seq.__iter__()</a>
从迭代器中获取下一个值
<code>next(seq)</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__next__" target="_blank">seq.__next__()</a>
按逆序创建一个迭代器
<code>reversed(seq)</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__reversed__" target="_blank">seq.__reversed__()</a>
无论何时创建迭代器都将调用 <code>__iter__()</code> 方法。这是用初始值对迭代器进行初始化的绝佳之处。
无论何时从迭代器中获取下一个值都将调用 <code>__next__()</code> 方法。
<code>__reversed__()</code> 方法并不常用。它以一个现有序列为参数并将该序列中所有元素从尾到头以逆序排列生成一个新的迭代器。
获取一个计算属性无条件的
<code>x.my_property</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__getattribute__" target="_blank">x.__getattribute__('my_property')</a>
获取一个计算属性后备
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__getattr__" target="_blank">x.__getattr__('my_property')</a>
设置某属性
<code>x.my_property = value</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__setattr__" target="_blank">x.__setattr__('my_property',value)</a>
删除某属性
<code>del x.my_property</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__delattr__" target="_blank">x.__delattr__('my_property')</a>
列出所有属性和方法
<code>dir(x)</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__dir__" target="_blank">x.__dir__()</a>
如果某个类定义了 <code>__getattribute__()</code> 方法在 每次引用属性或方法名称时 Python 都调用它特殊方法名称除外因为那样将会导致讨厌的无限循环。
如果某个类定义了 <code>__getattr__()</code> 方法Python 将只在正常的位置查询属性时才会调用它。如果实例 x 定义了属性color <code>x.color</code> 将 不会 调用<code>x.__getattr__('color')</code>而只会返回x.color 已定义好的值。
无论何时给属性赋值都会调用 <code>__setattr__()</code> 方法。
无论何时删除一个属性都将调用 <code>__delattr__()</code> 方法。
如果定义了 <code>__getattr__()</code> 或 <code>__getattribute__()</code> 方法 <code>__dir__()</code> 方法将非常有用。通常调用 <code>dir(x)</code> 将只显示正常的属性和方法。如果<code>__getattr()__</code>方法动态处理color 属性 <code>dir(x)</code> 将不会将 color 列为可用属性。可通过覆盖 <code>__dir__()</code> 方法允许将 color 列为可用属性对于想使用你的类但却不想深入其内部的人来说该方法非常有益。
序列的长度
<code>len(seq)</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__len__" target="_blank">seq.__len__()</a>
了解某序列是否包含特定的值
<code>x in seq</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__contains__" target="_blank">seq.__contains__(x)</a>
通过键来获取值
<code>x[key]</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__getitem__" target="_blank">x.__getitem__(key)</a>
通过键来设置值
<code>x[key] = value</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__setitem__" target="_blank">x.__setitem__(key,value)</a>
删除一个键值对
<code>del x[key]</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__delitem__" target="_blank">x.__delitem__(key)</a>
为缺失键提供默认值
<code>x[nonexistent_key]</code>
<a href="http://docs.python.org/3.1/library/collections.html#collections.defaultdict.__missing__" target="_blank">x.__missing__(nonexistent_key)</a>
我将此内容从前一节中拿出来使其单独成节是因为“比较”操作并不局限于数字。许多数据类型都可以进行比较——字符串、列表甚至字典。如果要创建自己的类且对象之间的比较有意义可以使用下面的特殊方法来实现比较。
相等
<code>x == y</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__eq__" target="_blank">x.__eq__(y)</a>
不相等
<code>x != y</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__ne__" target="_blank">x.__ne__(y)</a>
小于
<code>x < y</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__lt__" target="_blank">x.__lt__(y)</a>
小于或等于
<code>x <= y</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__le__" target="_blank">x.__le__(y)</a>
大于
<code>x > y</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__gt__" target="_blank">x.__gt__(y)</a>
大于或等于
<code>x >= y</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__ge__" target="_blank">x.__ge__(y)</a>
布尔上上下文环境中的真值
<code>if x:</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__bool__" target="_blank">x.__bool__()</a>
自定义对象的复制
<code>copy.copy(x)</code>
<a href="http://docs.python.org/3.1/library/copy.html" target="_blank">x.__copy__()</a>
自定义对象的深度复制
<code>copy.deepcopy(x)</code>
<a href="http://docs.python.org/3.1/library/copy.html" target="_blank">x.__deepcopy__()</a>
在 pickling 之前获取对象的状态
<code>pickle.dump(x, file)</code>
<a href="http://docs.python.org/3.1/library/pickle.html#pickle-state" target="_blank">x.__getstate__()</a>
序列化某对象
<a href="http://docs.python.org/3.1/library/pickle.html#pickling-class-instances" target="_blank">x.__reduce__()</a>
序列化某对象新 pickling 协议
<code>pickle.dump(x, file, protocol_version)</code>
<a href="http://docs.python.org/3.1/library/pickle.html#pickling-class-instances" target="_blank">x.__reduce_ex__(protocol_version)</a>
*
控制 unpickling 过程中对象的创建方式
<code>x = pickle.load(file)</code>
<a href="http://docs.python.org/3.1/library/pickle.html#pickling-class-instances" target="_blank">x.__getnewargs__()</a>
在 unpickling 之后还原对象的状态
<a href="http://docs.python.org/3.1/library/pickle.html#pickle-state" target="_blank">x.__setstate__()</a>
* 要重建序列化对象Python 需要创建一个和被序列化的对象看起来一样的新对象然后设置新对象的所有属性。<code>__getnewargs__()</code> 方法控制新对象的创建过程而 <code>__setstate__()</code> 方法控制属性值的还原方式。
在进入 <code>with</code> 语块时进行一些特别操作
<code>with x:</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__enter__" target="_blank">x.__enter__()</a>
在退出 <code>with</code> 语块时进行一些特别操作
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__exit__" target="_blank">x.__exit__()</a>
该文件对象同时定义了一个 <code>__enter__()</code> 和一个 <code>__exit__()</code> 方法。该 <code>__enter__()</code> 方法检查文件是否处于打开状态如果没有 <code>_checkClosed()</code>方法引发一个例外。
<code>__enter__()</code> 方法将始终返回 self —— 这是 <code>with</code> 语块将用于调用属性和方法的对象
在 <code>with</code> 语块结束后文件对象将自动关闭。怎么做到的在 <code>__exit__()</code> 方法中调用了 <code>self.close()</code> .
真正神奇的东西
如果知道自己在干什么你几乎可以完全控制类是如何比较的、属性如何定义以及类的子类是何种类型。
类构造器
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__new__" target="_blank">x.__new__()</a>
类析构器
<code>del x</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__del__" target="_blank">x.__del__()</a>
只定义特定集合的某些属性
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__slots__" target="_blank">x.__slots__()</a>
自定义散列值
<code>hash(x)</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__hash__" target="_blank">x.__hash__()</a>
获取某个属性的值
<code>x.color</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__get__" target="_blank">type(x).__dict__['color'].__get__(x, type(x))</a>
设置某个属性的值
<code>x.color = 'PapayaWhip'</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__set__" target="_blank">type(x).__dict__['color'].__set__(x, 'PapayaWhip')</a>
删除某个属性
<code>del x.color</code>
<a href="http://www.python.org/doc/3.1/reference/datamodel.html#object.__delete__" target="_blank">type(x).__dict__['color'].__del__(x)</a>
控制某个对象是否是该对象的实例 your class
<code>isinstance(x, MyClass)</code>
<a href="http://www.python.org/dev/peps/pep-3119/#overloading-isinstance-and-issubclass" target="_blank">MyClass.__instancecheck__(x)</a>
控制某个类是否是该类的子类
<code>issubclass(C, MyClass)</code>
<a href="http://www.python.org/dev/peps/pep-3119/#overloading-isinstance-and-issubclass" target="_blank">MyClass.__subclasscheck__(C)</a>
控制某个类是否是该抽象基类的子类
<code>issubclass(C, MyABC)</code>
<a href="http://docs.python.org/3.1/library/abc.html#abc.ABCMeta.__subclasshook__" target="_blank">MyABC.__subclasshook__(C)</a>
python中以双下划线的是一些系统定义得名称让python以更优雅得语法实行一些操作本质上还是一些函数和变量与其他函数和变量无二。
比如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__, 某些不可修改类型如setstr没有__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有意义时会调用
本文转自 AltBoy 51CTO博客,原文链接:http://blog.51cto.com/altboy/1945781