如何将类实例属性作为参数传递给类方法装饰器?
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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
