Here’s a brief overview of how each of these functions works:
-
getattr(object, name[, default]):- This function retrieves the value of the named attribute from the given object.
- If the attribute does not exist, it returns the value specified by the
defaultparameter if provided; otherwise, it raises anAttributeError. - Example:
class MyClass: def __init__(self): self.attribute = 'value' obj = MyClass() print(getattr(obj, 'attribute')) # Output: value print(getattr(obj, 'nonexistent', 'default')) # Output: default
-
setattr(object, name, value):- This function sets the value of the named attribute on the given object.
- If the attribute does not exist, it creates it.
- Example:
class MyClass: pass obj = MyClass() setattr(obj, 'attribute', 'value') print(obj.attribute) # Output: value
-
delattr(object, name):- This function deletes the named attribute from the given object.
- If the attribute does not exist, it raises an
AttributeError. - Example:
class MyClass: def __init__(self): self.attribute = 'value' obj = MyClass() delattr(obj, 'attribute') # print(obj.attribute) # This would raise an AttributeError
-
hasattr(object, name):- This function checks if the named attribute exists on the given object.
- It returns
Trueif the attribute exists, andFalseotherwise. - Example:
class MyClass: def __init__(self): self.attribute = 'value' obj = MyClass() print(hasattr(obj, 'attribute')) # Output: True print(hasattr(obj, 'nonexistent')) # Output: False
These functions are useful for dynamic attribute manipulation in Python objects.
