to modify the attributes of the Python namespace via:
- 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 namespace
is the namespace object, attr
is the attribute name, and new_value
is the new attribute value. 2. Using the setattr function can also use Python built-in functions setattr
to modify attribute values, for example:
pythonCopy code
setattr(namespace, 'attr', new_value)
where namespace
is the namespace object, attr
is the attribute name, and new_value
is 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 hasattr
the 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.