Python __getattr__与__setattr__使用方法
__getattr__和__setattr__可以用来对属性的设置和取值进行自定义处理,__str__则是字符串形式输出的时候进行自定义处理,
给出测试用例:
1 class Book(object):
2 def __setattr__(self,name,value):
3 if name == 'value':
4 object.__setattr__(self,name,value-100)
5 else:
6 object.__setattr__(self,name,value)
7
8 def __getattribute__(self,name):
9 try:
10 return object.__getattribute__(self,name)
11 except:
12 return name + "is not found"
13
14 def __str__(self):
15 return self.name + "cost:" + str(self.value)
16
17 c=Book()
18 c.name='xiaoxia'
19 c.value = 200
20 print c.name
21 print c
22 print c.value
23 print c.Type
24
25 输出结果:
26 xiaoxia
27 xiaoxiacost:100
28 100
29 Typeis not found
2 def __setattr__(self,name,value):
3 if name == 'value':
4 object.__setattr__(self,name,value-100)
5 else:
6 object.__setattr__(self,name,value)
7
8 def __getattribute__(self,name):
9 try:
10 return object.__getattribute__(self,name)
11 except:
12 return name + "is not found"
13
14 def __str__(self):
15 return self.name + "cost:" + str(self.value)
16
17 c=Book()
18 c.name='xiaoxia'
19 c.value = 200
20 print c.name
21 print c
22 print c.value
23 print c.Type
24
25 输出结果:
26 xiaoxia
27 xiaoxiacost:100
28 100
29 Typeis not found