getattr和setattr

>>> class MyData():
    
    def __init__(self,name,phone):
        self.name=name
        self.phone=phone
    def updatephone(self,newphone):
        self.phone=newphone
        print 'new phone is:',self.phone

        
>>> data=MyData()

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    data=MyData()
TypeError: __init__() takes exactly 3 arguments (1 given)

>>> data=MyData('xiaodeng',10086)

>>> dir(data)
['__doc__', '__init__', '__module__', 'name', 'phone', 'updatephone']


#获取属性值
>>> getattr(data,'name')
'xiaodeng'

>>> getattr(data,'phone')
10086

#设置属性值
>>> setattr(data,'name','xiaoDong')


>>> dir(data)
['__doc__', '__init__', '__module__', 'name', 'phone', 'updatephone']

>>> data.__dict__
{'phone': 10086, 'name': 'xiaoDong'}
>>> 

 

posted @ 2015-10-15 16:11  Xiao|Deng  阅读(453)  评论(0编辑  收藏  举报