Python basics === getattr() function usage


getattr(object, name[,default])


Get the property or method of the object object, print it out if it exists, print out the default value if it does not exist, and the default value is optional. It should be noted that if it is a method of the returned object, the memory address of the method is returned. If you need to run the method, you can add a pair of parentheses after it.

class test():
    name = "botoo"
    def __init__(self, age):
        self.age = age

    def say(self):
        print("i am",self.age,"years old")

t = test(18)
t.say()

print (getattr(t, " name " ))                #Get the name attribute and print it if it exists. 
print (getattr(t, " say " ))                      #Get the say method, print out the memory address of the method if it exists. 
getattr(t, " say " )()                                    #Get the say method, followed by parentheses to run this method. 
print (getattr(t, " gender " , " male " ))    #If the attribute does not exist, return a default value.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325121008&siteId=291194637