Comment passer un attribut d'instance de classe comme argument à un décorateur de méthode de classe ?

Patricia Arquette
Libérer: 2024-10-18 12:05:18
original
520 Les gens l'ont consulté

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()
Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!