Python天天美味(26) - __getattr__与__setattr__

__getattr__和__setattr__可以用来对属性的设置和取值进行处理,比如下面的例子:

class Book(object):
    
def __setattr__(self, name, value):
        
if name == 'value':
            object.
__setattr__(self, name, value - 100)
        
else:
            object.
__setattr__(self, name, value)
    
def __getattr__(self, name):
        
try:
            
return object.__getattribute__(name)
        
except:
            
return name + ' is not found!'
    
def __str__(self):
        
return self.name + ' cost : ' + str(self.value)

= Book()
c.name 
= 'Python'
c.value 
= 100
print c.name
print c.value
print c
print c.Type


上面的例子中,在赋值书的value属性时,偷偷的将value减去了100,呵。输出结果:

Python
0
Python cost : 0
Type is not found!

Python 天天美味系列(总)

Python 天天美味(24) - 初始化多维数组  

Python 天天美味(25) - 深入理解yield  

Python 天天美味(26) - __getattr__与__setattr__  

Python 天天美味(27) - 网络编程起步(Socket发送消息)  

Python 天天美味(28) - urlopen    

...

 

posted @ 2008-05-25 15:39  CoderZh  阅读(6512)  评论(18编辑  收藏  举报