跳至内容
Python 俱乐部
用户工具
登录
站点工具
搜索
工具
显示页面
修订记录
反向链接
最近更改
媒体管理器
网站地图
登录
>
最近更改
媒体管理器
网站地图
您的足迹:
python-class:special-function
本页面只读。您可以查看源文件,但不能更改它。如果您觉得这是系统错误,请联系管理员。
====== Python中类的特殊方法 ====== 一般说来,特殊的方法都被用来模仿某个行为。例如,如果你想要为你的类使用x[key]这样的索引操作(就像列表和元组一样),那么你只需要实现__getitem__()方法就可以了。想一下,Python就是对list类这样做的! 下面这个表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python参考手册》中找到一个庞大的列表。 <file> 名称 说明 --------------------------------------------------------- __init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。 __del__(self) 恰好在对象要被删除之前调用。 __str__(self) 在我们对对象使用print语句或是使用str()的时候调用。 __lt__(self,other) 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。 __getitem__(self,key) 使用x[key]索引操作符的时候调用。 __len__(self) 对序列对象使用内建的len()函数的时候调用。 __repr__(s) repr() and `...` conversions __cmp__(s, o) Compares s to o and returns <0, 0, or >0. Implements >, <, == etc... __hash__(s) Compute a 32 bit hash code; hash() and dictionary ops __nonzero__(s) Returns 0 or 1 for truth value testing __getattr__(s, name) called when attr lookup doesn't find <name> __setattr__(s, name, val) called when setting an attr (inside, don't use "self.name = value" use "self.__dict__[name] = val") __delattr__(s, name) called to delete attr <name> __call__(self, *args) called when an instance is called as function. </file>
python-class/special-function.txt
· 最后更改: 2010/06/02 01:18 (外部编辑)
页面工具
显示页面
修订记录
反向链接
回到顶部