类的专有方法(__getattr__和__setattr__、__delattr__)

时间:2021-11-10 10:48:13
# -*- coding: utf-8 -*-
#python 27
#xiaodeng
#http://www.360doc.com/content/15/0413/19/12067640_462966543.shtml #类的专有方法(__getattr__和__setattr__、__delattr__)
#__setattr__:通过该方法,给对象添加或修改指定的属性 class Test():
def __init__(self,name,age):
self.name=name
self.age=age test=Test('xiaodeng',28)
print test.name #setattr
#参数:(对象,属性,属性的值),如:setattr(object,name,value)
setattr(test,'python',2)
print test.__dict__#{'python': 2, 'age': 28, 'name': 'xiaodeng'} #getattr
#getattr(object,name,default)
print '**'*13
print getattr(test,'python')# delattr(test,'python')
print test.__dict__#{'age': 28, 'name': 'xiaodeng'}