Hasattr (object, name)
Determines whether an object has a Name property or a name method, returns a bool value, returns true with the name attribute, or FALSE.
It is important to note that name is enclosed in parentheses.
>>> class Test (): ... Name= "Xiaohua" ... def run (self): ... Return "Helloword" ...>>> t=test () >>> hasattr (t, "name") #判断对象有name属性True >>> hasattr (t, " Run ") #判断对象有run方法True >>>
GetAttr (object, Name[,default])
Gets the object's property or method, if it exists, prints the default value if it does not exist, and the default value is optional.
It is important to note that if you are returning the method of the object, the memory address of the method is returned, if you need to run this method,
You can add a pair of parentheses later.
>>> 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. ' @ ' >>>
SetAttr (object, name, values)
Assigns a value to the object's property and, if the property does not exist, first creates a re-assignment.
>>> 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 >>>
A comprehensive usage is to determine whether an object's properties exist and add 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 ") #可检测设置成功 ' + ' >> >
Zenyu
Source: http://www.cnblogs.com/cenyu/
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
If there are any errors in the text, please note. Lest more people be misled.
Python's hasattr () GetAttr () setattr () function uses a detailed approach