>  기사  >  백엔드 개발  >  클래스 인스턴스 속성을 클래스 메서드 데코레이터에 대한 인수로 전달하는 방법은 무엇입니까?

클래스 인스턴스 속성을 클래스 메서드 데코레이터에 대한 인수로 전달하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-18 12:05:18521검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.