一、闭包

  满足条件:

  1. 函数内嵌套一个函数;

  2.外层函数的返回值是内层函数的函数名;

  3.内层嵌套函数对外部作用域有一个非全局变量的引用;

def func():
print("===func====")
num=2
def wrapper():
print("------wrapper------")
print(num2) # 或者直接引用func的传参
return wrapper res=fun()
res()

  闭包的作用:实现数据锁定,不受外部影响。

二、装饰器

  开放封闭原则:面向对象的核心。软件实体应当是可扩展,而不可修改的。也就是说,对扩展是开放的,对修改是封闭的。

  装饰器:在不改变原来函数功能的情况下,进行扩展。同时,不改变调用方式。

  使用:@装饰器名称。 @为装饰器的语法糖

  常见应用场景:

    1. 权限校验,预判断是否有执行函数功能的权限;

    2. 计时,计算函数运行时间;

    3. 进行环境准备和恢复工作;

    4. web自动化用例失败截图;

#  示例4:失败截图装饰器
from selenium import webdriver browser=webdriver.Chrome()
browser.get("https://www.baidu.com") def decorator(func):
def wrapper():
try:
func()
except:
browser.save_screenshots("error.png")
raise e
return wrapper @decorator
def test_search():
browser.find_element_by_xpath("//input[@id='kw']").sendkeys("ninmen")
browser.find_element_by_xpath("//input[@id='su123']").click() test_search()

  1、普通装饰器

def decorator(func):
def wrapper():
print("----这是装饰器内层函数----")
func()
return wrapper @decorator # 等同于执行func = decorator(func)
def func():
print("====这是原功能函数====") func() # 此时,不改变调用方式的同时,实现了功能扩展

  2、带参数的装饰器

  3、通用装饰器

#带参数
def decorator(func):
def wrapper(a,b):
print("----这是装饰器内层函数----")
func(a,b)
return wrapper #通用
def decorator(func):
def wrapper(*args,**kwargs):
print("----这是装饰器内层函数----")
func(*args,**kwargs)
return wrapper @decorator # 等同于执行func = decorator(func)
def func(a,b):
print("====求和====",a+b) func()

  4、类实现装饰器

  __call__:魔术方法,在对象使用括号时被触发

class Decorator():
'''类实现通用的装饰器'''
def __init__(self,func):
self.func=func def __call__(self,*args,**kwargs):
print("----这是装饰器内层函数----")
return self.func(*args,**kwargs) @Decorator # 等同于执行func = Decorator(func)
def func(a,b):
print("====求和====",a+b)

  5、装饰器装饰类

class Decorator():
'''类实现通用的装饰器'''
def __init__(self,func):
self.func=func def __call__(self,*args,**kwargs):
print("----这是装饰器内层函数----")
return self.func(*args,**kwargs) @Decorator # 等同于执行func = Decorator(Hero)
class Hero:
def func(a,b):
print("====求和====",a+b) h=Hero()
h.func() #也可以使用 2中的通用装饰器
def decorator(func):
def wrapper(*args,**kwargs):
print("扩展功能")
obj=func(*args,**kwargs)
return obj #返回类对象
return wrapper @decorator # 等同于执行func = decorator(Hero)
class Hero:
def func(a,b):
print("====求和====",a+b) h=Hero()
h.func()

  6、三个内置的装饰器

  1、@property 将某函数,做为属性使用

  property可以将python定义的函数当做属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的

  只有@property表示只读。
  同时有@property和@x.setter表示可读可写。
  同时有@property和@x.setter和@x.deleter表示可读可写可删除。

class Foo:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError('name must be str')
self.__name = value
@name.deleter
def name(self):
raise TypeError('can not delete')
f = Foo('jack')
print(f.name) # jack
f.name = 'hanmeimei'
print(f.name) # hanmeimei
# del f.name # TypeError: can not delete

  2、@classmethod 修饰类的方式:仅仅与类交互而不和实例交互,类在使用时会将类本身当做参数传给类方法的第一个参数

  带修饰类方法:cls做为方法的第一个参数,隐式的将类做为对象,传递给方法,调用时无须实例化。

  普通函数方法:self做为第一个参数,隐式的将类实例传递给方法,调用方法时,类必须实例化。

class Date:

    def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day @classmethod
def now(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday) def __str__(self):
return '%s-%s-%s' % (self.year, self.month, self.day) e = Date.now()
print(e) # 2018-8-1

  3、@staticmethod 修饰类的方式

  1) 静态方法和在普通的非class的method作用是一样的,只不过是命名空间是在类里面。

  2) 一般使用场景就是和类相关的操作,但是又不会依赖和改变类、实例的状态,比如一些工具方法。

class Date:

    def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day @staticmethod
def now():
t = time.localtime()
return Date(t.tm_year, t.tm_mon, t.tm_mday) def __str__(self):
return '%s-%s-%s' % (self.year, self.month, self.day) e = Date.now()
print(e) # 2018-8-1

python进阶(三)~~~装饰器和闭包的更多相关文章

  1. Python进阶(六)----装饰器

    Python进阶(六)----装饰器 一丶开放封闭原则 开放原则: ​ 增加一些额外的新功能 封闭原则: ​ 不改变源码.以及调用方式 二丶初识装饰器 装饰器: ​ 也可称装饰器函数,诠释开放封闭原则 ...

  2. python进阶04 装饰器、描述器、常用内置装饰器

    python进阶04 装饰器.描述器.常用内置装饰器 一.装饰器 作用:能够给现有的函数增加功能 如何给一个现有的函数增加执行计数的功能 首先用类来添加新功能 def fun(): #首先我们定义一个 ...

  3. Python进阶之装饰器

    函数也是对象 要理解Python装饰器,首先要明白在Python中,函数也是一种对象,因此可以把定义函数时的函数名看作是函数对象的一个引用.既然是引用,因此可以将函数赋值给一个变量,也可以把函数作为一 ...

  4. python函数下篇装饰器和闭包,外加作用域

    装饰器和闭包的基础概念 装饰器是一种设计模式能实现代码重用,经常用于查日志,性能测试,事务处理等,抽离函数大量不必的功能. 装饰器:1.装饰器本身是一个函数,用于装饰其它函数:2.功能:增强被装饰函数 ...

  5. Python进阶: Decorator 装饰器你太美

    函数 -> 装饰器 函数的4个核心概念 1.函数可以赋与变量 def func(message): print('Got a message: {}'.format(message)) send ...

  6. python学习-42 装饰器 --- 函数闭包1

    函数闭包举例: def father(name): print('hello world') def son(): print('儿子说:我的爸爸是%s' % name) def grandfson( ...

  7. python进阶:装饰器

    1.闭包 简单理解:闭包就是多层函数的嵌套,外层函数的返回值是内层函数的引用. def out_func(n): num = 100 def in_fucn(*args,**kwargs): # no ...

  8. [Python进阶]002.装饰器(1)

    装饰器(1) 介绍 HelloWorld 需求 使用函数式编程 加入装饰器 解析 介绍 Python的装饰器叫Decorator,就是对一个模块做装饰. 作用: 为已存在的对象添加额外功能. 与Jav ...

  9. Python进阶(装饰器)

    from datetime import datetime def log(func):#func表示装饰器作用于的函数 def wrapper(*args,**kw):#wrapper返回装饰器作用 ...

随机推荐

  1. IDEA中利用MAVEN制作和打包普通可执行应用(非SprintBoot的WEB应用)

    我使用IDEA也就半年,开发中常常会遇到一些问题,例如用IDEA编写普通的可执行程序: 之前使用Eclipse编写一个可执行的JAVA程序,然后导出打包,非常方便: 但是我呢,想在 IDEA 中用Ma ...

  2. mybatis-generator-plugin

    1.背景 这篇文章刚开始想着哪个分类呢?mybatis.idea或是maven呢,最后还是选择了mybatis.最初使用这个逆向工具是在eclipse上,使用的是eclispe上mbg插件执行配置ge ...

  3. DataTable.Copy()

    DataTable dtpocopy = dtPO.Copy(); DataRow[] dr = dtpocopy .Select("客户名称='" + cusName + &qu ...

  4. Xilinx Vivado器件分配管脚:LVDS差分电平信号如何分配管脚?

    最近在把Quartus Prime 15.1的工程移植到Vivado 2019.1,需要改变的地方还是很多的,先记一下差分信号在FPGA中的收发管脚定义和配置.以LVDS信号为例吧. 在7 Serie ...

  5. android 使用 git 进行版本控制

    远程建立仓库 vcs --> import into version control --> create git respository 选中整个工程(project 页面) vcs - ...

  6. UVA - 1626 Brackets sequence (区间dp)

    题意:给定一个串,可能空串,或由'[',']','(',')'组成.问使其平衡所需添加最少的字符数,并打印平衡后的串. 分析:dp[i][j]表示区间(i,j)最少需添加的字符数. 1.递推. #in ...

  7. C++(五)构造函数

    //构造函数的作用:就是在函数被创建时使用特定的值构造对象,将对象初始化为一个特定的初始状态//例如在构造一个clock类对象的时候,将初始的时间设定为0:0:0//构造函数的名必须与类名相同,不能定 ...

  8. bzoj 2281: [Sdoi2011]黑白棋

    再次,,,,,虚(一开始看错题了,看成一次移动一个棋子,能移动1-d个格子...这样的话有没有大神会做??本蒟蒻就教) 额,,直接%%%%把...http://hzwer.com/5760.html ...

  9. 一个swift版简单的用户名和密码输入textField

    http://www.code4app.com/thread-31992-1-1.html 常见的动画提交按钮 http://www.code4app.com/thread-32239-1-1.htm ...

  10. 逆向--C函数和汇编

    C函数和汇编 C代码 (编译工具gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609平台ubuntu i386 32位) int bar(int c ...