- Python has hasattr,setattr,delattr related to getattr, so let's talk about their usage in detail in the following example.
class Xiaorui: def __init__ (self): = ' Fengyun ' def SetName (self,name): = name def GetName (self): return self.name def greet (self): Print "Hello,i ' m%s"%self.name = Xiaorui ()
I. Hasattr (OBJECT,NAME)
BOOL Determines if the object has a name attribute, for example:
foo = Xiaorui ()
Hasattr (foo, ' SetName ') #判断setName是否存在, the presence returns TRUE.
Two. GetAttr (Object,name,default)
If the name attribute (method) exists, returns the value of name (method address) Otherwise returns the default value.
GetAttr (foo, ' name ', ' NA ') #存在name属性, so return its value
' Fengyun '
GetAttr (foo, ' age ', ' NA ')
' NA '
One will find that he is in fact the same as the direct object.name usage.
Three. SetAttr (Object,name,default)
SetAttr (foo, ' age ', ' 18 ') #
The string may list an existing attribute (or a new property). This function assigns a value to the property's
. Similar to Foo.age = 18
GetAttr (foo, ' age ', ' not find ')
' 18 '
SetAttr (foo, ' work ', ' Student ') #
You can use the SetAttr method to set the work variable of Foo to student
GetAttr (foo, ' work ', ' not find ')
' Student '
Four. Delattr (object, ' name ')
Delattr (foo, ' name ') #删除属性name, the original value is ' Fengyun '
GetAttr (foo, ' name ', ' not find ')
' Not find '
Python reflection function