Home > Article > Backend Development > How to Implement Dynamic Attribute Access with __getattr__-like Behavior in Modules?
To extend a module with __getattr__-like functionality that dynamically creates instances of a class and invokes methods on them when accessing attributes that do not exist in the module.
While getattr methods commonly operate on classes, it is not directly applicable to modules. To address this, a wrapper function can be implemented to redirect attribute access to an instance of a substitution class.
<code class="python">class Wrapper: def __init__(mod): setattr(mod, '__getattr__', getattrmod)</code>
This wrapper class provides a customized getattr method called getattrmod.
<code class="python">sys.modules[__name__] = Wrapper</code>
By replacing the module itself with the wrapper, any future attribute access on the module will be intercepted by the getattr method.
<code class="python">def getattrmod(mod, attr): # Create an instance of the substitution class instance = Class() # Invoke the method with the same name as the missing attribute return getattr(instance, attr)</code>
The above is the detailed content of How to Implement Dynamic Attribute Access with __getattr__-like Behavior in Modules?. For more information, please follow other related articles on the PHP Chinese website!