文章目录

  • 一、什么是 python 装饰器
  • 二、装饰器的使用
  • 三、装饰器类型
    • 3.1 特性装饰器 @property
    • 3.2 类装饰器 @classmethod
    • 3.3 静态装饰器 @staticmethod
    • 3.4 抽象方法装饰器 @abstractmethod

一、什么是 python 装饰器

装饰器是一个 python 的函数,可以让其他函数在不增加任何代码的情况下增加功能,也就是将其他函数“包装”起来,可以简化代码,做到代码重用。

装饰器能接收一个函数作为输入,返回值也是一个函数对象。

二、装饰器的使用

例子来源

def a_new_decorator(a_func):def wrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunctiondef a_function_requiring_decoration():print("I am the function which needs some decoration to remove my foul smell")a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

从上面这个例子可以看出,装饰器就是能把扔进他的函数做一个装饰。@符号是装饰器的语法糖,使用@符号的写法如下:

@a_new_decorator
def a_function_requiring_decoration():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

我们都知道函数有一些原信息,如 docstring, _ _name _ _等,如果使用装饰器的话,原函数的元信息就会被装饰器的信息所代替,如下所示:

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

所以 python 提供了一个装饰器:functools.wrapswraps 本身就是一个装饰器,能把原函数的元信息拷贝到装饰器函数中,使得装饰器函数有和原函数一样的元信息。

from functools import wrapsdef a_new_decorator(a_func):@wraps(a_func)def wrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")return wrapTheFunction@a_new_decorator
def a_function_requiring_decoration():"""Hey yo! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

所以,典型的蓝本如下:

from functools import wraps
def decorator_name(f):@wraps(f)def decorated(*args, **kwargs):if not can_run:return "Function will not run"return f(*args, **kwargs)return decorated@decorator_name
def func():return("Function is running")can_run = True
print(func())
# Output: Function is runningcan_run = False
print(func())
# Output: Function will not run

三、装饰器类型

常见的内置装饰器有三种:

  • @property
  • @staticmethod
  • @classmethod

3.1 特性装饰器 @property

@property: 可以把一个方法变成其同名属性,以支持实例访问和调用

在函数前面加上 @property 后,就可以把 gettersetter 方法变成属性,定义 getter 方法就是一个只读属性,定义 setter 方法就是一个可读可写的。

class Student(object):@propertydef score(self):return self._score@score.setterdef score(self, value):if not isinstance(value, int):raise ValueError('score must be an integer!')if value < 0 or value > 100:raise ValueError('score must between 0 ~ 100!')self._score = value
# birth 是可读写属性,age 是只读属性,注意这里 birth 函数返回的是 self._birth,不能返回 self.birth
class Student(object):@propertydef birth(self):return self._birth@birth.setterdef birth(self, value):self._birth = value@propertydef age(self):return 2015 - self._birth

3.2 类装饰器 @classmethod

@classmethod : 用来指定一个类的方法为类方法,其修饰的方法不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等

传入的 cls 通常用作类方法的第一参数,对于普通的类来说,要使用的话必须先进行实例化,而在一个类中,某个函数前面加上了 classmethod 或 staticmethod,这个函数就可以不用实例化,可以直接通过类名进行调用。

class A:@classmethoddef func(cls, arg1, arg2):...

例子:

import time
class Date:def __init__(self, year, month, day):self.year = yearself.month = monthself.day = day@classmethoddef today(cls):t = time.localtime()return cls(t.tm_year, t.tm_mon, t.tm_mday)

调用:

a = Date(2020, 4, 6)
b = Date.today()

3.3 静态装饰器 @staticmethod

改变一个方法为静态方法,静态方法不需要传递隐性的第一参数,静态方法的本质类型就是一个函数。

静态方法可以直接通过类进行调用,也可以通过实例进行调用:

import time
class Date:def __init__(self,year,month,day):self.year=yearself.month=monthself.day=day@staticmethoddef now(): #用Date.now()的形式去产生实例,该实例用的是当前时间t=time.localtime() #获取结构化的时间格式return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回@staticmethoddef tomorrow():#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间t=time.localtime(time.time()+86400)return Date(t.tm_year,t.tm_mon,t.tm_mday)
a = Data(2020, 4, 6)
print(a.year, a.month, a.day)
# 静态方法无需实例化
b = Data.now()
print(b.year, b.month, b.day)
c = Data.tomorrow
print(c.year, c.month, c.day)
# 静态方法也可实例化后调用
a.now()

3.4 抽象方法装饰器 @abstractmethod

抽象方法表示基类的中一个方法,在基类中没有实现,所以不能被实例化,在子类中实现了以后才能被实例化,继承了含有抽象方法基类类的子类必须复写所有的抽象方法,未被 @abstractmethod 修饰的可以不重写。

abstractmethod 的好处在哪里:

可以把某个方法装饰成抽象的方法,类似于接口,可以用具有同一属性的对象实现同一个抽象的方法,这样无论是维护还是从代码结构来说,都比较清晰。

from abc import ABC, abstractmethod
class a(ABC):@abstractmethoddef writeblog(self):pass
class b(a):def writeblog(self):print('writing blogs')if __name__=='__main__':# 使用如下的方法会报错,因为被抽象装饰器装饰的方法需要不能直接实例化c = a()# 可以让 b 继承 a,然后在 b 里边重写被装饰的 writeblog 的方法,然后实例化 bc = b()c.writeblog() # output 'writing blogs'

【python 8】python 装饰器相关推荐

  1. python装饰器原理-python 中的装饰器及其原理

    装饰器模式 此前的文章中我们介绍过装饰器模式: 装饰器模式中具体的 Decorator 实现类通过将对组建的请求转发给被装饰的对象,并在转发前后执行一些额外的动作来修改原有的部分行为,实现增强 Com ...

  2. python装饰器类-PYTHON里的装饰器能装饰类吗

    扩展回答 如何理解python里的装饰器 通常可以理解它是一个hook 的回调函数. 或者是理解成python 留给二次开发的一个内置API. 一般是用回调和hook 方式实现的. 如何理解Pytho ...

  3. python类装饰器详解-python 中的装饰器详解

    装饰器 闭包 闭包简单的来说就是一个函数,在该函数内部再定义一个函数,并且这个内部函数用到了外部变量(即是外部函数的参数),最终这个函数返回内部函数的引用,这就是闭包. def decorator(p ...

  4. python中的装饰器decorator

    python中的装饰器 装饰器是为了解决以下描述的问题而产生的方法 我们在已有的函数代码的基础上,想要动态的为这个函数增加功能而又不改变原函数的代码 例如有三个函数: def f1(x):return ...

  5. python生成器和装饰器_python之yield与装饰器

    防伪码:忘情公子著 python中的yield: 在之前发布的<python之列表解析与生成器>中我们有提到过,生成器所实现的是跟列表解析近似的效果,但是我们不能对生成器做一些属于列表解析 ...

  6. 二十一、深入Python强大的装饰器

    @Author: Runsen 文章目录 闭包 装饰器 嵌套函数的装饰器 带参数嵌套函数的装饰器 类装饰器 嵌套装饰器 @Date:2019年07月11日 最近有同学在问关于Python中装饰器的问题 ...

  7. Python闭包与装饰器

    Python闭包与装饰器 一.闭包       函数是一个对象,所以可以对象的形式作为某个函数的结果返回.函数执行完后内部变量将会被回收.在闭包中,由于内部函数存在对外部函数的变量的引用,所以即使外部 ...

  8. python高级语法装饰器_Python高级编程——装饰器Decorator超详细讲解上

    Python高级编程--装饰器Decorator超详细讲解(上篇) 送你小心心记得关注我哦!! 进入正文 全文摘要 装饰器decorator,是python语言的重要特性,我们平时都会遇到,无论是面向 ...

  9. Python深入05 装饰器

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 装饰器(decorator)是一种高级Python语法.装饰器可以对一个函数.方法 ...

  10. Python如何创建装饰器时保留函数元信息

    问题 你写了一个装饰器作用在某个函数上,但是这个函数的重要的元信息比如名字.文档字符串.注解和参数签名都丢失了. 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语法过后, ...

最新文章

  1. 通过TCP/IP连接Mysql数据库
  2. 【MM模块】 Goods Receipt 收货 4
  3. 飞机大作战游戏 1----(运用H5和Js制作)
  4. 关于jinja2的{{...|safe}}过滤器
  5. python学习笔记--迭代器
  6. python最简易入门_零基础入门python,用最简单的方式即可入门python,没有那么复杂...
  7. mysql数据库用户简单分析_如何用SQLyog来分析MySQL数据库详解
  8. 当TIME_WAIT状态的TCP正常挥手,收到SYN后…
  9. 【深度学习】有效防止过拟合
  10. Java IO-InputStream家族 -装饰者模式
  11. USBCAN、CAN分析仪、CANCANFD综合测试分析软件LKMaster主要功能一览
  12. java poi pdf实例_java通过poi导出excel和pdf
  13. 如何运用阿里巴巴国际站进行数据分析?
  14. 手把手教你写电商爬虫-第五课 京东商品评论爬虫 一起来对付反爬虫
  15. Zabbix:Lack of free swap space on Zabbix server 解决
  16. 苹果cms怎么采集别人网站的视频
  17. colbat strike 安装注意事项
  18. 02-nation.sql
  19. ASP.Net中常见的文件类型
  20. 交换机hybrid模式

热门文章

  1. encryption
  2. node.js的下载,安装以及卸载
  3. [Cocos2d-x For WP8]Hello world
  4. poj 3522 Slim Span
  5. 巨一自动化工业机器人_2021第11届深圳国际工业自动化及机器人展览会
  6. powershell 遍历json_使用PowerShell处理JSON字符串
  7. C++轻量级微服务_从微服务架构解析信源新一代“金融e采”产品
  8. python如何将utf-8编码文件改为ansi编码文件_Excel导入CSV文件乱码?两个小方法让文件正常显示...
  9. matlab 动态库 二次调用,LINUX matlab编译动态库调用崩溃
  10. [蓝桥杯]算法提高 道路和航路(spfa+deque+快读优化)