python类操作符重载

Demo

setattr & getattr
1
2
3
4
5
6
7
8
9
10
11
12
13
class ():
def __setattr__(self, n, v):
if n == 'age':
self.__dict__[n] = v
print 'setattr'

def __getattr__(self, n):
if n == 'age':
return self.__dict__[n]

obj = Object()
obj.age = 2
print obj.age

输出:

output
1
2
setattr
2

参考资料

1、 http://blog.teamtreehouse.com/operator-overloading-python

2、 所有的操作符
https://docs.python.org/3/reference/datamodel.html#special-method-names