Home >Backend Development >Python Tutorial >How to Pass a Class Field to a Decorator on a Class Method as an Argument?

How to Pass a Class Field to a Decorator on a Class Method as an Argument?

DDD
DDDOriginal
2024-10-18 12:03:56415browse

How to Pass a Class Field to a Decorator on a Class Method as an Argument?

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.

The above is the detailed content of How to Pass a Class Field to a Decorator on a Class Method as an Argument?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn