Use an example to illustrate the usage of these four functions:
First a simple class as follows:
class Animal(object): def __init__(self,name, zone): self.name = name self.zone = zone def bark(self): print("The %s id barking..." % self.name)
hasattr(object, name)
determines whether an object has a name attribute or a name method, returns a BOOL value, and returns True if there is a name attribute, otherwise returns False.
Note that the name should be enclosed in quotation marks.
>>> dog = Animal("Dog", "earth") >>> print(dog.name) Dog >>> print(hasattr(dog, "name")) True >>> print(hasattr(dog, "bark")) True >>> print(hasattr(dog, "color")) False
getattr(object, name[,default])
Get the attribute or method of the object object, if it exists, print it out, if it does not exist, print out the default value, 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.
>>> print(getattr(dog, "name", "None")) Dog >>> print (getattr(dog, " bark " )) <bound method Animal.bark of < __main__ .Animal object at 0x0000000002A5C898>> #Print out the memory address of this method >>> getattr(dog, " bark " )( ) #Add parentheses to execute this method The Dog id barking...
setattr(object, name, values)
assigns a value to the attribute of the object. If the attribute does not exist, create it first and then assign it.
>>> setattr(dog, " name " , " cat " ) #Assign object attributes >>> print (dog.name) cat >>> setattr(dog, " age " ,4) #If the object attribute does not exist, create this attribute, and then assign it >>> print (dog.age) 4
delattr(object, name) #delete the corresponding attribute
>>> print(hasattr(dog, "bark")) True delattr(dog, " bark " ) print (hasattr(dog, " bark " )) # #This step reports an error, there is no bark attribute, it has been deleted!
Reference blog post address: https://www.cnblogs.com/cenyu/p/5713686.html