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

DDD
Release: 2024-10-18 12:03:56
Original
318 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!