Decorating Class Methods with Self Arguments
To pass a class field to a decorator on a class method as an argument, it's necessary to access the field at runtime rather than at class definition time. Here's how:
1. Intercept the Method Arguments
The decorator can intercept the method arguments using a wrapper function. The first argument to the wrapper will be the instance (self).
<code class="python">def check_authorization(f): def wrapper(*args): print(args[0].url) return f(*args) return wrapper</code>
2. Use Getattr to Access Field Dynamically
Alternatively, the field name can be passed to the decorator as a string and accessed using getattr:
<code class="python">def check_authorization(attribute): def _check_authorization(f): def wrapper(self, *args): print(getattr(self, attribute)) return f(self, *args) return wrapper return _check_authorization</code>
With this method, the decorator can be called with the desired attribute name as an argument.
Example
<code class="python">@check_authorization("url") def get(self): do_work()</code>
In this example, the decorator will access the url attribute of the instance at runtime.
以上是如何将类字段作为参数传递给类方法上的装饰器?的详细内容。更多信息请关注PHP中文网其他相关文章!