如何將類別實例屬性作為參數傳遞給類別方法裝飾器?

Patricia Arquette
發布: 2024-10-18 12:05:18
原創
519 人瀏覽過

How to pass a class instance attribute as an argument to a class method decorator?

Decorator with Instance Attribute Argument for Class Methods

Question

Could you assist me with passing a class field to a class method decorator as an argument? Specifically, what I'm trying to achieve is the following:

class Client:
    def __init__(self, url):
        self.url = url

    @check_authorization("some_attr", self.url)
    def get(self):
        do_work()
登入後複製

However, I'm encountering an error indicating that "self" does not exist when attempting to pass "self.url" to the decorator. Is there a solution to this issue?

Solution

Certainly. Here's a way you can accomplish your desired behavior:

Instead of specifying the instance attribute during class definition, you can evaluate it dynamically at runtime:

def check_authorization(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()
http://www.google.com
get
登入後複製

The decorator captures the method's parameters. The first parameter refers to the instance, and you access the attribute from it.

You can also provide the attribute name as a string to the decorator and use "getattr" if you prefer not to hardcode it:

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
登入後複製

以上是如何將類別實例屬性作為參數傳遞給類別方法裝飾器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!