82. Dynamic Attribute Access with __getattr__
The __getattr__ method in Python allows you to define custom behavior for attribute access. It's called when an attribute that does not exist is accessed. This is useful for dynamic attribute handling, like creating "virtual" attributes, or logging attribute access.
Here are 10 Python code snippets demonstrating various ways to use __getattr__:
1. Basic Usage of __getattr__ for Undefined Attributes
class MyClass:
def __getattr__(self, name):
return f"Attribute '{name}' not found!"
obj = MyClass()
print(obj.some_attribute) # This will call __getattr__ since 'some_attribute' does not exist2. Handling Default Values with __getattr__
You can use __getattr__ to provide default values when an attribute is accessed but does not exist.
class MyClass:
def __getattr__(self, name):
return "Default Value"
obj = MyClass()
print(obj.non_existent) # Output will be "Default Value"3. Simulating Read-Only Attributes with __getattr__
You can use __getattr__ to simulate read-only attributes by intercepting the attribute access.
4. Creating Virtual Attributes with __getattr__
You can dynamically generate virtual attributes that don't actually exist.
5. Logging Attribute Access with __getattr__
You can log or track attribute access.
6. Accessing Non-Existent Attributes for Method Call Simulation
You can simulate method calls for attributes that are not defined.
7. Raising Custom Exceptions with __getattr__
You can raise custom exceptions when accessing certain attributes.
8. Accessing Nested Attributes Dynamically
You can use __getattr__ to implement dynamic access to nested attributes, useful in cases like working with JSON-like structures.
9. Using __getattr__ for Dynamic Method Resolution
You can use __getattr__ for resolving method names dynamically.
10. Caching Computed Attributes Using __getattr__
You can cache computed values in the __getattr__ method to improve performance.
These examples demonstrate the versatility of __getattr__ in handling dynamic behavior for attribute access, from providing default values, simulating methods, to handling nested structures and caching.
Last updated