首頁 > 後端開發 > Python教學 > 如何在 Python 中將實例屬性傳遞給類別方法裝飾器?

如何在 Python 中將實例屬性傳遞給類別方法裝飾器?

Barbara Streisand
發布: 2024-10-18 11:55:02
原創
870 人瀏覽過

How to Pass Instance Attributes to Class Method Decorators in Python?

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板