首页  >  文章  >  后端开发  >  实例属性可以作为参数传递给 Python 中的类方法装饰器吗?

实例属性可以作为参数传递给 Python 中的类方法装饰器吗?

Barbara Streisand
Barbara Streisand原创
2024-10-18 12:02:36781浏览

Can Instance Attributes be Passed as Arguments to Class Method Decorators in Python?

将类字段传递给类方法装饰器

在 Python 中,可以使用带有附加参数的装饰器来装饰类方法。但是,当尝试将实例属性作为参数传递给这些装饰器时,会出现问题。

考虑以下示例:

<code class="python">class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization("some_attr", self.url)
    def get(self):
        do_work()</code>

目的是将 self.url 属性传递给 check_authorization 装饰器。但是,Python 会引发错误,表明 self 在类定义范围内不存在。

解决方案

要解决此问题,可以将属性检查推迟到运行时通过拦截装饰器中的方法参数。包装函数的第一个参数将是实例,允许访问实例属性。

<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()
# Output: http://www.google.com
#          get</code>

替代方法

或者,可以通过传递动态访问属性将属性名称作为装饰器的字符串。这消除了对特定属性名称进行硬编码的需要。

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

以上是实例属性可以作为参数传递给 Python 中的类方法装饰器吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn