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'} >>>
无语言基础,自学python所做的各种笔记,欢迎大牛指点.