Python __getattr__与__setattr__使用方法
2010-08-04 17:24
731 查看
__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
作者:xiaoxia
出处:http://cnblogs.com/xiaoxia
我的淘宝:http://shop62115161.taobao.com/
本文遵从GNU 的自由文档许可证(Free Document License)的条款,欢迎转载、修改、散布。
给出测试用例:
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
作者:xiaoxia
出处:http://cnblogs.com/xiaoxia
我的淘宝:http://shop62115161.taobao.com/
本文遵从GNU 的自由文档许可证(Free Document License)的条款,欢迎转载、修改、散布。
相关文章推荐
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- 【转】Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法
- python 中__setattr__, __getattr__,__getattribute__, __call__使用方法
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python标准库:内置函数hasattr() getattr() setattr() 函数使用方法详解
- Python __getattr__与__setattr__使用方法
- Python中hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python __getattr__与__setattr__使用方法
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python __getattr__与__setattr__使用方法
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解
- Python的hasattr() getattr() setattr() 函数使用方法详解