美文网首页
python -装饰器

python -装饰器

作者: ddm2014 | 来源:发表于2018-09-01 22:44 被阅读0次

装饰器之前要先说说函数名()和函数名的区别

def test():
  print(2)
  return 2

test()是返回函数值,所以是可以赋值给变量的。比如a=test()。
test是调用函数,在scrapy里有很多的callback=self.parse
,就是调用具体函数。
装饰器是由里外两层函数,一般里面的函数是主函数,比如网页里各个网页,外层函数是里层函数执行前后要执行的函数,比如看网页之前要看你登陆没有这种。
通用格式是:

def outer_func(func):
  def inner_func(*args, **kwargs):
    #dosomething before the actual func
    result = actual_func(*args, **kwargs)
    #dosomething with resule before the actual func
    return result
  return inner_fun

调用是这样的

@outer_func
def actual_func(*args, **kwargs):
  #blalala...

actual_func()

如果要传参给外层函数则是这样的:

def outer_func(decorator_args):
  def args_func(func):
    def inner_func(*args, **kwargs):
      #dosomething before the actual func
      result = actual_func(*args, **kwargs)
      #dosomething with resule before the actual func
      return result
    return inner_func
  return args_func

@outer_func(decorator_args)
def actual_func(*args, **kwargs):
  #blalala...

相关文章

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • Python中的装饰器

    Python中的装饰器 不带参数的装饰器 带参数的装饰器 类装饰器 functools.wraps 使用装饰器极大...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • Python 装饰器填坑指南 | 最常见的报错信息、原因和解决方

    Python 装饰器简介装饰器(Decorator)是 Python 非常实用的一个语法糖功能。装饰器本质是一种返...

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • python3基础---详解装饰器

    1、装饰器原理 2、装饰器语法 3、装饰器执行的时间 装饰器在Python解释器执行的时候,就会进行自动装饰,并不...

  • 2019-05-26python装饰器到底是什么?

    装饰器例子 参考语法 装饰器是什么?个人理解,装饰器,是python中一种写法的定义。他仍然符合python的基本...

  • 2018-07-18

    Python装饰器 装饰,顾名思义,是用来打扮什么东西的。Python装饰...

网友评论

      本文标题:python -装饰器

      本文链接:https://www.haomeiwen.com/subject/nzcuyftx.html