如何将类字段作为参数传递给类方法上的装饰器?

DDD
发布: 2024-10-18 12:03:56
原创
318 人浏览过

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.

以上是如何将类字段作为参数传递给类方法上的装饰器?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!