Decorating Class Methods with Self Arguments
In Python, class methods can be decorated to add additional behaviors or validate their arguments. However, passing the instance attribute as an argument to the decorator can be challenging.
To address this, one solution is to retrieve the attribute value dynamically at runtime within the decorator. Here's how you can achieve this:
<code class="python">from functools import wraps def check_authorization(f): @wraps(f) def wrapper(*args): print(args[0].url) return f(*args) return wrapper class Client: def __init__(self, url): self.url = url @check_authorization def get(self): print('get') Client('http://www.google.com').get()</code>
In this example, the check_authorization decorator intercepts the method arguments and retrieves the instance's URL attribute from the first argument (which is the instance itself). You can then use the attribute's value within the decorator to perform any necessary authorization checks.
For greater flexibility, you can modify the decorator to accept the attribute name as a parameter:
<code class="python">def check_authorization(attribute): def _check_authorization(f): @wraps(f) def wrapper(self, *args): print(getattr(self, attribute)) return f(self, *args) return wrapper return _check_authorization</code>
This allows you to specify the attribute name to be checked at runtime, giving you more control over the decoration process.
以上是如何在 Python 中將實例屬性傳遞給類別方法裝飾器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!