Reflection / introspection: program can access, modify the ability to detect and the state itself or behavior.
python, offers four functions:
hasattr (obj, name) whether obj method does not have a corresponding string or attribute name
getattr (obj, name (, default)) until the value in the name of obj
When setattr (obj, name, value) in the name of the set value value obj
delattr (obj, name) delete the name value in the obj
class BlackMedium: feture='ugly' def __init__(self,name1,addr): self.name=name1 self.addr=addr def sell_hourse(self): print('%s正在卖房'%self.name) def rent_hourse(self): print('%s租房子'%self.name) b1=BlackMedium('zyk','sh') r= the hasattr (b1, ' name ' ) Print (R & lt) S = the hasattr (b1, ' sell_hourse ' ) # query b1 can call attribute class BlackMedium in Print (S) W1 = getattr (b1, ' name ' ) # with b1.name w2 of getattr = (B1, ' rent_hourse ' ) # no default parameters if no error will W3 = getattr (B1, ' ABC ' , ' do not have this property ' ) # If not, the default parameters feedback Print ( W1, W2, W3) # W2 is a function of address w2 of () b1.sb = True # vertical two methods can be used, provided the modified functionality setattr (B1, ' SB2 ' , False) Print (B1. the __dict__ ) del b1.sb delattr (B1, ' SB2 ' ) # delete Print (b1. __dict__ )
》》》
True
True
Zyk <Method BlackMedium.rent_hourse of bound <__ __ BlackMedium main AT 0x102097dd8 >> Object no such property.
Zyk renting
{ 'name': 'zyk' , 'addr': 'sh', 'sb': True, 'sb2 ': False}
{' name ':' Zyk ',' addr ':' SH '}