python魔术方法
2013-10-22 14:05
253 查看
在类中有一些特殊的方法具有特殊的意义,比如
一般说来,特殊的方法都被用来模仿某个行为。例如,如果你想要为你的类使用
下面这个表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python参考手册》中找到一个庞大的列表。
表15.1 一些特殊的方法
例如:“
x=Person();
>>x[1] 输出1
>>x[2]输出2
>>x["abc"] 输出"abc"
def __str__(self):
return 'this is a string'
print x 或str(x)输出 'this is a string'.
python魔术方法大全:
https://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/a-guide-to-pythons-magic-methods.html
http://woodpecker.org.cn/diveintopython3/special-method-names.html
__init__和
__del__方法,它们的重要性我们已经学习过了。
一般说来,特殊的方法都被用来模仿某个行为。例如,如果你想要为你的类使用
x[key]这样的索引操作(就像列表和元组一样),那么你只需要实现
__getitem__()方法就可以了。想一下,Python就是对
list类这样做的!
下面这个表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python参考手册》中找到一个庞大的列表。
表15.1 一些特殊的方法
名称 | 说明 |
---|---|
__init__(self,...) | 这个方法在新建对象恰好要被返回使用之前被调用。 |
__del__(self) | 恰好在对象要被删除之前调用。 |
__str__(self) | 在我们对对象使用str()的时候调用。 |
__lt__(self,other) | 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。 |
__getitem__(self,key) | 使用x[key]索引操作符的时候调用。 |
__len__(self) | 对序列对象使用内建的len()函数的时候调用。 |
class Person: def __getitem__(self,key): self.key=key; print self.key
x=Person();
>>x[1] 输出1
>>x[2]输出2
>>x["abc"] 输出"abc"
def __str__(self):
return 'this is a string'
print x 或str(x)输出 'this is a string'.
python魔术方法大全:
https://pycoders-weekly-chinese.readthedocs.org/en/latest/issue6/a-guide-to-pythons-magic-methods.html
http://woodpecker.org.cn/diveintopython3/special-method-names.html
相关文章推荐
- Python学习笔记:魔术方法详解
- Python魔术方法-Magic Method
- python进阶----魔术方法
- Python 魔术方法(Magic Method)
- Python 魔术方法指南
- python 理解_str_魔术方法
- Python 魔术方法指南
- Python 魔术方法及调用方式
- [python]魔术方法
- Python 魔术方法指南
- python-魔术方法
- python 魔术方法:__getitem__、__setitem__、__delitem__、__len__
- 【编程语言】Python 魔术方法指南
- Python中的魔术(双下划线'__xxx__')方法详解
- Python魔术方法
- Python 魔术方法指南
- Python魔术方法-Magic Method
- Python 魔术方法指南
- Python魔术方法详解
- python魔术方法之装饰器