One, Hasattr (object, name)
Determines whether an object has a Name property or a name method, returns a bool value, has the Name property or method returns True, otherwise returns false.
>>> class Test (): ... Name= "Xiaohua" ... def run (self): ... Return "Helloword" ...>>> t=test () >>> hasattr (t, "name") #判断对象有name属性True >>> hasattr (t, " Run ") #判断对象有run方法True >>>
Ii. GetAttr (object, Name[,default])
Gets the property or method of the object;
If a property value exists, the property value can be printed (returned), and if there is a method, the memory address of the method (which can be appended with a pair of parentheses (), the Calling method), and a non-existent property, or an error if the default value is set.
>>> class Test (): ... Name= "Xiaohua" ... def run (self): ... Return "Helloword" ...>>> t=test () >>> getattr (t, "name") #获取name属性, the presence is printed out. ' Xiaohua ' >>> getattr (t, "Run") #获取run方法, there is a memory address for printing out the method. <bound method Test.run of <__main__.test instance at 0x0269c878>>>>> getattr (T, "Run") () # Gets the Run method, which is followed by parentheses to run the method. ' Helloword ' >>> getattr (t, "age") #获取一个不存在的属性. Traceback (most recent): File ' <stdin> ', line 1, in <module>attributeerror:test instance have no Attribute ' age ' >>> getattr (t, "age", "Max") #若属性不存在, returns a default value. ' @ ' >>>
Third, SetAttr (object, name, values)
Assigns a value to the object's property, and if the property does not exist, first create a second assignment.
no return value.
>>> class Test (): ... Name= "Xiaohua" ... def run (self): ... Return "Helloword" ...>>> t=test () >>> hasattr (T, "age") #判断属性是否存在False >>> setattr (t, " Age "," ") #为属相赋值, and no return value >>> hasattr (t," age ") #属性存在了True >>>
Iv. Integrated Use
Determines whether an object property exists and adds the property if it does not exist.
>>> class Test (): ... Name= "Xiaohua" ... def run (self): ... Return "Helloword" ...>>> t=test () >>> getattr (T, "age") #age属性不存在Traceback ): File "<stdin>", line 1, in <module>attributeerror:test instance have no attribute ' age ' >>> ge Tattr (T, "age", SetAttr (T, "age", "") ") #age属性不存在时, set the property ' + ' >>> getattr (t," age ") #可检测设置成功 ' + ' >> >
Python attribute function analysis-hasattr (), GetAttr (), SetAttr ()