Modify the attributes of the python namespace

to modify the attributes of the Python namespace via:

  1. Assigning values ​​directly to attributes You can directly use assignment statements to assign values ​​to attributes, for example:
 
 

pythonCopy code

namespace.attr = new_value

where namespaceis the namespace object, attris the attribute name, and new_valueis the new attribute value. 2. Using the setattr function can also use Python built-in functions setattrto modify attribute values, for example:

 
 

pythonCopy code

setattr(namespace, 'attr', new_value)

where namespaceis the namespace object, attris the attribute name, and new_valueis the new attribute value. It should be noted that both of the above methods will create a new attribute if the attribute does not exist. If the attribute to be modified does not exist, you can use hasattrthe function to judge, for example:

 
 

pythonCopy code

if hasattr(namespace, 'attr'): setattr(namespace, 'attr', new_value) else: # 处理属性不存在的情况

Among them, hasattr(namespace, 'attr')a boolean value is returned, indicating whether the attribute exists.

Guess you like

Origin blog.csdn.net/ihateright/article/details/131135059