python之函数用法setattr(),了解即可

# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#python之函数用法setattr(),了解即可
#http://www.cnblogs.com/hongfei/p/3858256.html



#setattr()
#说明:给object对象添加新的name(属性)和value(属性值),通常在class中运用较多
'''
setattr(...)
    setattr(object, name, value)
    
    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.
'''



#案例
class Student():
    def __init__(self,name,age):
        self.name=name
        self.age=age
        
    def __str__(self):
        return self.name
        
student=Student('xiaodeng',28)
print student                   #xiaodeng
print student.name              #xiaodeng
print student.age               #28


#setattr
setattr(student,'set','1')
print student.__dict__          #{'age': 28, 'set': '1', 'name': 'xiaodeng'}



#__setattr__;通常在class中运用较多

 

posted @ 2015-11-07 18:27  Xiao|Deng  阅读(2988)  评论(0编辑  收藏  举报