首页 > 编程语言 >Python - Class Decorators

Python - Class Decorators

时间:2024-07-31 16:29:47浏览次数:8  
标签:__ function Python MyDecorator class call func Decorators Class

We have used functions to decorate functions and to decorate classes. Now, we will see how to define a class as a decorator.

At the start of this chapter, in the definition of decorator, we had seen that a decorator is a callable; a callable is any object that can be called a function. If a class has the __call__ method defined inside it, then instance objects of that class become callable objects. When these instance objects are called like a function using parentheses, the code inside the __call__ method is executed. Now, let us see how we can use such a class as a decorator.

class MyDecorator:
    def __init__(self, fn):
        self.fn = fn

    def __call__(self,*args, **kwargs):
        print('Decoration before execution of function') 
        self.fn(*args, **kwargs)
        print('Decoration after execution of function\n') 


def func(message, name):
    print(message, name)

func = MyDecorator(func)

The class MyDecorator is going to serve as a decorator. We have a simple function named func and we have decorated it using the class MyDecorator by using the manual decoration syntax. In the statement func = MyDecorator(func), we are sending the undecorated function to the class and getting back the decorated function. We know that when we call a class object ( MyDecorator(func) ), the __init__ method of the class is executed. This is why we have made __init__ method accept a function. The call MyDecorator(func) returns an instance object of the class. So, after the statement func = MyDecorator(func), func is actually an instance object of the MyDecorator class.

So, this is how we can create a decorator class. The second parameter to __init__ accepts the function to be decorated, and this function is stored as an instance variable. Inside the __call__ method the original undecorated function is called and the decoration code is also placed before or after the call. The class is instantiated at the decoration time, and the instance object that is created is assigned to the function name. After decoration, the function name refers to an instance object, and so when the function name is called, the __call__ method of the class is executed.

Instead of using the manual decoration statement, we can use the automatic decoration syntax to get the same effect.

@MyDecorator
def func(message, name):
    print(message, name)

 

You can return the result from the __call__ method, so that the return value of the original function is not lost.

def __call__(self,*args, **kwargs):
    print('Decoration before execution of function') 
    result = self.fn(*args, **kwargs)
    print('Decoration after execution of function\n') 

    return result

If you want to preserve the metadata, then you have to call the wraps decorator.

def __init__(self, fn):
    self.fn = fn
    wraps(fn)(self)
    self.author = 'Jim'   # Add a new attribute here

If you want the decorator to add an attribute to the function, you have to add it inside the __init__ method, not inside the __call__ method. This is because we do not want to add the attribute each time the function is called. We want to add the attribute just once when the function is decorated.

 

标签:__,function,Python,MyDecorator,class,call,func,Decorators,Class
From: https://www.cnblogs.com/zhangzhihui/p/18334926

相关文章

  • 基于Python的高校成绩分析【源码+LW+PPT+部署讲解】
    作者主页:编程千纸鹤作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待......
  • 基于Python网络爬虫的电子产品信息查询可视化系统
    作者主页:编程千纸鹤作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待......
  • [SUCTF 2019]Pythonginx (unicode转IDNA域名分割漏洞)
    代码我看到这两个就感觉有问题了,第一个转编码这个搜了一下是unicode转idna的问题,第二个urlopen是Python标准库中urllib.request模块中的一个函数,用于向指定的URL发送HTTP请求并获取响应参考文章:https://xz.aliyun.com/t/6070?time__1311=n4%2BxnD0DgDcmG%3DrDsYoxCqiIQ7KDtH......
  • 基于Python的高校成绩分析【源码+LW+PPT+部署讲解】
    作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待与各位高校教师、企......
  • 基于Python网络爬虫的电子产品信息查询可视化系统
    作者简介:Java领域优质创作者、CSDN博客专家、CSDN内容合伙人、掘金特邀作者、阿里云博客专家、51CTO特邀作者、多年架构师设计经验、多年校企合作经验,被多个学校常年聘为校外企业导师,指导学生毕业设计并参与学生毕业答辩指导,有较为丰富的相关经验。期待与各位高校教师、企业......
  • 使用 Python 读取 .xlsx 文件的最快方法
    我正在尝试使用Python将.xlsx文件中的数据读入MySQL数据库。这是我的代码:wb=openpyxl.load_workbook(filename="file",read_only=True)ws=wb['MyWorksheet']conn=MySQLdb.connect()cursor=conn.cursor()cursor.execute("SETautocommit=0"......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-60 - 判断元素是否显示 - 下篇
    1.简介有些页面元素的生命周期如同流星一闪,昙花一现。我们也不知道这个元素在没在页面中出现过,为了捕获这一美好瞬间,让其成为永恒。我们就来判断元素是否显示出现过。在操作元素之前,可以先判断元素的状态。判断元素操作状态也可以用于断言。2.常用的元素判断方法2.1page对象调......
  • 是否有可能在Python中获取客户端计算机的位置
    我想编写一个程序,用python查找客户端计算机的位置。不过,我不介意它的格式如何。我到处尝试过一些东西,但老实说,我对这类事情了解不多,所以我真的不知道从哪里开始。|||我想简单地运行该程序,并将运行该程序的客户端计算机的位置写入控制台。Iwouldliketosimplyrunt......
  • Python:使用 Selenium WebDriver 无法在客户端打开浏览器
    我使用SeleniumWebDriver开发了一个应用程序来打开一些页面。它在本地工作得很好,但我还需要在客户端启动浏览器。我使用Apache2underUbuntu18部署了应用程序。driver=webdriver.Chrome(executable_path="chromedriver",chrome_options=ch......
  • Python:使用默认模块在python中读取excel
    我有Python2.6.6版本,但无法安装pandas、xlrd、xlwt等新模块。我想使用Python读取Excel。是否可以使用Python中存在的默认模块读取Excel。抱歉,不能使用Python2.6.6的默认模块读取Excel文件。Python没有内置的功能来处理Excel文件。使用外部库(如提......