Detailed usage of python hasattr() getattr() setattr() function

Posted by Steppio on Sat, 27 Jun 2020 18:17:18 +0200

hasattr(object, name) function:

Determines whether an object has a name attribute or a name method, returns a bool value, returns True with a name attribute, or returns False.

Note: name should be enclosed in parentheses.

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'name')  #Determine whether an object has name Properties, True

res = hasattr(functiondemo, "run") #Determine whether an object has run Method, True

res = hasattr(functiondemo, "age") #Determine whether an object has age Properties, Falsw
print(res)

 

getattr(object, name[,default]) function:

Gets the property or method of the object, prints it if it exists, or prints the default value if it does not exist, which is optional.

Note: If the object's method is returned, the printed result is the memory address of the method, and if you need to run this method, you can add parentheses () after it.

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
getattr(functiondemo, 'name') #Obtain name Attributes, print out when present--- demo 

getattr(functiondemo, "run") #Obtain run Method, there is the memory address of the print out method---<bound method function_demo.run of <__main__.function_demo object at 0x10244f320>>

getattr(functiondemo, "age") #Get a property that does not exist with the following error:
Traceback (most recent call last):
  File "/Users/liuhuiling/Desktop/MT_code/OpAPIDemo/conf/OPCommUtil.py", line 39, in <module>
    res = getattr(functiondemo, "age")
AttributeError: 'function_demo' object has no attribute 'age'

getattr(functiondemo, "age", 18)  #Gets a property that does not exist and returns a default value

 

setattr(object, name,values) function:

Assign a value to an object's property. If the property does not exist, create it before assigning it.

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'age')  # judge age Whether the property exists, False
print(res)

setattr(functiondemo, 'age', 18 )  #Yes age Attribute assignment, no return value

res1 = hasattr(functiondemo, 'age') #Judging again whether the attribute exists, True
print(res1)

 

Comprehensive use:

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'addr') # First determine if there is any
if res:
    addr = getattr(functiondemo, 'addr')
    print(addr)
else:
    addr = getattr(functiondemo, 'addr', setattr(functiondemo, 'addr', 'Beijing Capital'))
    #addr = getattr(functiondemo, 'addr', 'Xuchang, Henan')
    print(addr)

Welcome comments to ~~~

Topics: Python Attribute