Home >Backend Development >Python Tutorial >How to Pass Class Field to Class Method Decorator

How to Pass Class Field to Class Method Decorator

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 12:23:03400browse

How to Pass Class Field to Class Method Decorator

Passing Class Field to Class Method Decorator

When attempting to pass a class field to a decorator on a class method, you may encounter an error stating that the field does not exist. This arises because you are attempting to pass the field at the time of class definition, but it may not be available at that stage.

Solution 1: Runtime Check

To resolve this, consider checking the field at runtime instead. This can be achieved by modifying the decorator to intercept the method arguments, where the first argument will be the instance. The instance attribute can then be accessed using .:

<code class="python">def check_authorization(f):
    def wrapper(*args):
        print(args[0].url)
        return f(*args)
    return wrapper

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

    @check_authorization
    def get(self):
        print('get')

Client('http://www.google.com').get()</code>

Solution 2: Attribute Name as String

If you wish to avoid hardcoding the attribute name in the decorator, you can pass it as a string:

<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>

The above is the detailed content of How to Pass Class Field to Class Method Decorator. 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