浅谈解除装饰器作用(python3新增)

yipeiwu_com6年前Python基础

一个装饰器已经作用在一个函数上,你想撤销它,直接访问原始的未包装的那个函数。

假设装饰器是通过 @wraps 来实现的,那么你可以通过访问 wrapped 属性来访问原始函数:

>>> @somedecorator
>>> def add(x, y):
...  return x + y
...
>>> orig_add = add.__wrapped__
>>> orig_add(3, 4)
7
>>>

如果有多个包装器:

In [588]: from functools import wraps

In [589]: def decorator1(func):
  ...:  @wraps(func)
  ...:  def wrapper(*args, **kwargs):
  ...:   print ('Decorator 1')
  ...:   return func(*args, **kwargs)
  ...:  return wrapper
  ...: 

In [590]: def decorator2(func):
  ...:  @wraps(func)
  ...:  def wrapper(*args, **kwargs):
  ...:   print ('Decorator 2')
  ...:   return func(*args, **kwargs)
  ...:  return wrapper
  ...: 

In [591]: @decorator1
  ...: @decorator2
  ...: def add(x, y):
  ...:  return x+y
  ...: 

In [592]: add(2,3)
Decorator 1
Decorator 2
Out[592]: 5

In [593]: add.__wrapped__(2, 3)
Decorator 2
Out[593]: 5

In [594]: add.__wrapped__.__wrapped__(2,3)
Out[594]: 5

参考:Python Cookbook

以上这篇浅谈解除装饰器作用(python3新增)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用OpenCV circle函数图像上画圆的示例代码

OpenCV中circle与rectangle函数显示,只不过rectangle在图像中画矩形,circle在图像中画圆。 void circle(Mat img, Point ce...

Python如何读取MySQL数据库表数据

Python如何读取MySQL数据库表数据

本文实例为大家分享了Python读取MySQL数据库表数据的具体代码,供大家参考,具体内容如下 环境:Python 3.6 ,Window 64bit 目的:从MySQL数据库读取目标表...

python实现巡检系统(solaris)示例

使用python + shell 编写,是一个简易solaris系统巡检程序 复制代码 代码如下:#!/usr/bin/python -u#-*- coding:utf-8 -*-''...

python 如何去除字符串头尾的多余符号

在读文件时常常得到一些\n和引号之类的符号,可以使用字符串的成员函数strip()来去除。 1.去除首尾不需要的字符 a= '"This is test string"' #...

对于Python深浅拷贝的理解

对于Python深浅拷贝的理解

1,浅拷贝是什么? 浅拷贝是对于一个对象的顶层拷贝,通俗的理解是:拷贝了引用,并没有拷贝内容 通过a=b这种方式赋值只是赋值的引用(内存地址),a和b都指向了同一个内存空间,所...