美文网首页
Decorator in Python

Decorator in Python

作者: Infoceiver | 来源:发表于2016-03-18 12:09 被阅读0次

First look at what a decorator code really is doing.
The following two blocks of code are same:

@dec
def func():
  pass

and

def func():
  pass
func = dec(func)

Where dec is pre-defined function:

def dec(f):
  def wrapped(*args, **kwargs):
        pass # wrapped has f and args pass to f;
             # may call f() and do something else
  return wrapped

So when you evoke the function func, what is really call is wrapped function produced by dec, and args will be pass to new function wrapped and also original function func will get involved in wrapped.

The purpose of the decorator is to customize or decorate a set of the functions when you define them so that the function decorated will share some common operations. The decorated function will do what is designed to do by decorator, instead of only finishing what this function is designed to do.


Few Examples (common usages)

HTML

def p_decorate(func):
   def func_wrapper(name):
       return "<p>{0}</p>".format(func(name))
   return func_wrapper

def strong_decorate(func):
    def func_wrapper(name):
        return "<strong>{0}</strong>".format(func(name))
    return func_wrapper

def div_decorate(func):
    def func_wrapper(name):
        return "<div>{0}</div>".format(func(name))
    return fun_wrapper

@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
   return "lorem ipsum, {0} dolor sit amet".format(name)

print get_text("John")

# Outputs <div><p><strong>lorem ipsum, John dolor sit amet</strong></p></div>

Decorator Function (passing args to decorator)

def tags(tag_name):
    def tags_decorator(func):
        def func_wrapper(name):
            return "<{0}>{1}</{0}>".format(tag_name, func(name))
        return func_wrapper
    return tags_decorator

@tags("p")
def get_text(name):
    return "Hello "+name

print get_text("John")

# Outputs <p>Hello John</p>

More To Learn

相关文章

  • python常用的装饰器

    Python中有很多装饰器(decorator),可以减少冗余代码。Decorator本质上也是函数,只是它的参数...

  • Python中的Decorator装饰器

    Decorator 装饰器 理解decorator(装饰器)的关键, 在于理解在python中函数是第一公民, 并...

  • Python Decorator

    利用装饰器记录函数运行时间 list去空s=['A', '', 'B', None, 'C', ' ']s=...

  • Python Decorator

    flask中有很多装饰器,今天来整理下Python中装饰器的相关概念。 1. 最简单的装饰器 我们常常可以看到类似...

  • Decorator in Python

    First look at what a decorator code really is doing.The f...

  • Python decorator

    话说昨天面试python开发的时候,做了一个笔试题。 本来以为自己还算有python开发经验的,但是一真正测试才发...

  • 【Python】decorator

    decorator @ 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外...

  • python decorator

    实现一个log的decorator,使它既支持: 也支持: 实现: 使用log 装饰器装饰方法: 输出: @wra...

  • TypeError: 'NoneType' object is

    Python在使用decorator时,报错TypeError: 'NoneType' object is not...

  • JavaScript装饰器 Decorator

    前言 许多面向对象都有decorator(装饰器)函数,比如python中也可以用decorator函数来强化代码...

网友评论

      本文标题:Decorator in Python

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