Hasattr (object, name) function:
Determines whether an object has a Name property or a name method, returns a bool value, returns true with the Name property, or False otherwise.
Note: name is enclosed in parentheses.
classFunction_demo (): Name='Demo' defRun (self):return "Hello function"Functiondemo=Function_demo () Res=hasattr(Functiondemo,'name')#determines whether the object has a Name property, TrueRes=hasattr(Functiondemo,"Run")#determines whether the object has a Run method, TrueRes=hasattr(Functiondemo," Age")#determines whether an object has an age attribute, FALSWPrint(RES)
GetAttr (object, Name[,default]) function:
Gets the object's property or method, prints it if it exists, and prints the default value if it does not exist, optional.
Note: If you return an object method, the print result is the memory address of the method, and if you need to run the method, you can add parentheses () later
classFunction_demo (): Name='Demo' defRun (self):return "Hello function"Functiondemo=Function_demo () getattr (Functiondemo,'name')#get the Name property, print it out---demogetattr (Functiondemo,"Run")#Gets the memory address of the Run method, which is printed out---<bound method Function_demo.run of <__main__.function_demo object at 0x10244f320> >getattr (Functiondemo," Age")#gets the property that does not exist, with the following error:Traceback (most recent): File"/users/liuhuiling/desktop/mt_code/opapidemo/conf/opcommutil.py", line 39,inch<module>Res= GetAttr (Functiondemo," Age") Attributeerror:'Function_demo'object has no attribute' Age'getattr (Functiondemo," Age", 18)#gets the property that does not exist, returns a default value
SetAttr (object, name,values) function:
Assigns a value to the object's property and, if the property does not exist, first creates a re-assignment.
classFunction_demo (): Name='Demo' defRun (self):return "Hello function"Functiondemo=Function_demo () Res= Hasattr (Functiondemo,' Age')#to determine if the Age property exists, FalsePrint(res) setattr (Functiondemo,' Age', 18)#Assignment to the Age property, no return valueres1= Hasattr (Functiondemo,' Age')#again to determine if the property exists, TruePrint(RES1)
Comprehensive use:
classFunction_demo (): Name='Demo' defRun (self):return "Hello function"Functiondemo=Function_demo () Res= Hasattr (Functiondemo,'Addr')#first determine if there isifres:addr= GetAttr (Functiondemo,'Addr') Print(addr)Else: Addr= GetAttr (Functiondemo,'Addr', SetAttr (Functiondemo,'Addr','Beijing Capital')) #addr = getattr (Functiondemo, ' addr ', ' Henan Xuchang ') Print(addr)
Welcome Comments ~ ~ ~
Python hasattr () getattr () SetAttr () function is used in a detailed way