关于Python中的操作符重载,可以查看2.7.3文档地址:
http://docs.python.org/reference/datamodel.html#special-method-names
或者一篇详细的中文教程:
Python 魔术方法指南
类可以重载python的操作符,操作符重载使我们的对象与内置的一样。__X__的名字的方法是特殊的挂钩(hook),python通过这种特殊的命名来拦截操作符,以实现重载。 python在计算操作符时会自动调用这样的方法,例如:如果对象继承了__add__方法,当它出现在+表达式中时会调用这个方法。通过重载,用户定义的对象就像内置的一样。
在类中重载操作符
- 操作符重载使得类能拦截标准的python操作。
- 类可以重载所有的python的表达式操作符。
- 类可以重载对象操作:print,函数调用,限定等。
- 重载使得类的实例看起来更像内置的。
- 重载是通过特殊命名的类方法来实现的。
魔术方法、调用方式、解释:
- __new__(cls [,…])
instance = MyClass(arg1, arg2)
__new__ 在创建实例的时候被调用
- __init__(self [,…])
instance = MyClass(arg1, arg2)
__init__ 在创建实例的时候被调用
- __cmp__(self, other)
self == other, self > other, 等。
在比较的时候调用
- __pos__(self)
+self
一元加运算符
- __neg__(self)
-self
一元减运算符
- __invert__(self)
~self
取反运算符
- __index__(self)
x[self]
对象被作为索引使用的时候
- __nonzero__(self)
bool(self)
对象的布尔值
- __getattr__(self, name)
self.name # name 不存在
访问一个不存在的属性时
- __setattr__(self, name, val)
self.name = val
对一个属性赋值时
- __delattr__(self, name)
del self.name
删除一个属性时
- __getattribute__(self, name)
self.name
访问任何属性时
- __getitem__(self, key)
self[key]
使用索引访问元素时
- __setitem__(self, key, val)
self[key] = val
对某个索引值赋值时
- __delitem__(self, key)
del self[key]
删除某个索引值时
- __iter__(self)
for x in self
迭代时
- __contains__(self, value)
value in self, value not in self
使用 in 操作测试关系时
- __concat__(self, value)
self + other
连接两个对象时
- __call__(self [,…])
self(args)
“调用”对象时
- __enter__(self)
with self as x:
with 语句环境管理
- __exit__(self, exc, val, trace)
with self as x:
with 语句环境管理
- __getstate__(self)
pickle.dump(pkl_file, self)
序列化
- __setstate__(self)
data = pickle.load(pkl_file)
序列化
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# coding:utf-8
#__getitem__拦截了所有的索引操作
class
Obj
:
#重载操作符的写法,这里重载了下标操作符
def
__getitem__
(
self
,
index
)
:
return
index *
*
2
#取得indexer的对象
x
=
Obj
(
)
for
i
in
range
(
5
)
:
#x[i]将调用__getitem__(x,i)
print
x
[
i
]
|
调用结果:
1
2
3
4
5
|
0
1
4
9
16
|