码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-11-07 18:53:14      阅读:430      评论:0      收藏:0      [点我收藏+]

标签:

# -*- 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中运用较多

 

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

标签:

原文地址:http://www.cnblogs.com/dengyg200891/p/4945840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!