heading python decorator

decorator make a wrapper function do something before and after the original function. The wrapper function share arguments with original function.@decorator is same with?func = decorator(func);?decorator receive func and return a wrapper func with same arguments with original func. The decorator function is done in @decorator progress.?Wrapper fucntion in decorator share the same argument with original function and run the original function in itself. If you want decotrator receive some arguements(as decorator receiv function arguemnt return arguments funcion), you need the decotrator return a maker function which receive argument and return wrapper function(same arguments with original function). The sample is as follows.

  • so a maker functions will return wrapper function with arguments same with original fucntion.
  • We user maker functions to receive arguments for wrapper functions. So wrapper functions can do something with some other arguments.

In?[67]:

def mydecorator_maker(*args, **kwargs):
    print "this is decorator maker function..."
    print args, kwargs
    def mydecorator(func):
        print "this is decorator... args is passed here"
        print args, kwargs
        def decorator_wrapper(func_arg1, func_arg2):
            print "this is decorator wrapper, before function..."
            print "func_arg1 " + func_arg1 + " func_arg2 " + func_arg2
            func(func_arg1, func_arg2)
            print "this is decorator wrapper, after function"
        return decorator_wrapper
    return mydecorator

@mydecorator_maker(1, 2, 3, test="test")
def mydecorated_function(func_arg1, func_arg2):
    print "this is decorated function with arg1 " + func_arg1 + " arg2 " + func_arg2

?

this is decorator maker function...
(1, 2, 3) {‘test‘: ‘test‘}
this is decorator... args is passed here
(1, 2, 3) {‘test‘: ‘test‘}

?

This is another example for decorated doecorator. It works also with maker and with interation. Nothing special from above maker function

In?[1]:

def decorator_with_args(decorator_to_enhance):
    """
    This function is supposed to be used as a decorator.
    It must decorate an other function, that is intended to be used as a decorator.
    Take a cup of coffee.
    It will allow any decorator to accept an arbitrary number of arguments,
    saving you the headache to remember how to do that every time.
    """  

    # We use the same trick we did to pass arguments
    def decorator_maker(*args, **kwargs):  

        # We create on the fly a decorator that accepts only a function
        # but keeps the passed arguments from the maker.
        def decorator_wrapper(func):  

            # We return the result of the original decorator, which, after all,
            # IS JUST AN ORDINARY FUNCTION (which returns a function).
            # Only pitfall: the decorator must have this specific signature or it won‘t work:
            return decorator_to_enhance(func, *args, **kwargs)  

        return decorator_wrapper  

    return decorator_maker

In?[2]:

# You create the function you will use as a decorator. And stick a decorator on it :-)
# Don‘t forget, the signature is "decorator(func, *args, **kwargs)"
@decorator_with_args
def decorated_decorator(func, *args, **kwargs):
    def wrapper(function_arg1, function_arg2):
        print "Decorated with", args, kwargs
        return func(function_arg1, function_arg2)
    return wrapper  

# Then you decorate the functions you wish with your brand new decorated decorator.  

@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
    print "Hello", function_arg1, function_arg2  

decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything  

# Whoooot!

?

Decorated with (42, 404, 1024) {}
Hello Universe and everything

In?[3]:

decorated_decorator = decorator_with_args(decorated_decorator)

?

I will use a decorated docorator to receive arguments instend of maker functions. I think this is a really realization of intetraion.

  • Decorator means a function change from orginal function to wrapper function in decorator function.
  • The decorater function here will be change to a function do something with arguments and return the deocrator(which change original fucntion to wrapper).
  • We can make this change by a decorated decorator.
  • The decorated decorator receive decorator return a enhancer function dothing something with arguments. The function return the decorator at last. The enchancer function provide a enhacement to decorator with ablity to do something with some arguments.

In?[71]:

def decorator_enhance_decorator(decorator_to_enhancement):
    print "This decorated decorator will enhance decorator function..."
    print decorator_to_enhancement
    #def decorator_enhancer(*args, **kwargs):
    def decorator_enhancer(*args, **kwargs):
        print "decorator enhancer do something with args..."
        print args
        print kwargs
        return decorator_to_enhancement
    return decorator_enhancer
    #return decorator_enhance_maker

@decorator_enhance_decorator
def decorated_decorator3(func):
    print func
    print "func is decorated here"
    def wrapper(func_arg1, func_arg2):
        print "wrapper with arg1 " + func_arg1 + " and arg2 " + func_arg2
        return func(func_arg1, func_arg2)
    return wrapper

@decorated_decorator3(1, 2, 3, test="test")
def decorated_function3(func_arg1, func_arg2):
    print "decorated function with func arg1 " + func_arg1 + " arg2" + func_arg2
    print "do something in decorated function"

decorated_function3("Liliy", "Baby")

?

This decorated decorator will enhance decorator function...
<function decorated_decorator3 at 0x10b7755f0>
decorator enhancer do something with args...
(1, 2, 3)
{‘test‘: ‘test‘}
<function decorated_function3 at 0x10b775668>
func is decorated here
wrapper with arg1 Liliy and arg2 Baby
decorated function with func arg1 Liliy arg2Baby
do something in decorated function

In?[47]:

mydecorated_function("liliy", "funny")

?

this is decorator wrapper, before function...
func_arg1 liliy func_arg2 funny
this is decorated function with arg1 liliy arg2 funny
this is decorator wrapper, after function
时间: 2024-11-04 15:00:31

heading python decorator的相关文章

python decorator心得体会

python decorator心得体会 前言 用途 给方法添加新的功能 给类增加或者删除方法 参数化的decorator 更改方法的默认调用行为 2和3的整合 其实1和4可以归为一类特性,都是对现有方法的增强.** 前言 此小短文来源于qq群一位朋友的问题,问题如下: 下面这段代码的功能是什么? def log(func): def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw)

python -- decorator &amp;&amp; generator &amp;&amp; iterator

python -- decorator && generator && iterator 一. decorator 1. 2. 二. generator 三. iterator 原文地址:https://www.cnblogs.com/-cjzsr-/p/8167923.html

python decorator 基础

转自:http://www.cnblogs.com/xybaby/p/6274187.html 一般来说,装饰器是一个函数,接受一个函数(或者类)作为参数,返回值也是也是一个函数(或者类).首先来看一个简单的例子: # -*- coding: utf-8 -*- 2 def log_cost_time(func): 3 def wrapped(*args, **kwargs): 4 import time 5 begin = time.time() 6 try: 7 return func(*a

python decorator的本质

推荐查看博客:python的修饰器 对于Python的这个@注解语法糖- Syntactic Sugar 来说,当你在用某个@decorator来修饰某个函数func时,如下所示: @decorator def func(): pass 其解释器会解释成下面这样的语句: func = decorator(func) 是的,上面这句话在真实情况下执行了.如果我们执行以下代码: def fuck(fn): print "fuck %s!" % fn.__name__[::-1].upper

Python decorator module

Python functool Python中的装饰器 def _memoize(func, *args, **kw): if kw: # frozenset is used to ensure hashability key = args, frozenset(kw.items()) else: key = args cache = func.cache # attribute added by memoize if key not in cache: cache[key] = func(*a

python decorator 进阶

转自:http://www.cnblogs.com/xybaby/p/6274283.html 上一篇文章开始的时候提到 "一般来说,装饰器是一个函数,接受一个函数(或者类)作为参数,返回值也是也是一个函数(或者参数)" 有一般情况,就有特殊情况.第一种特殊情况:装饰器可能也是一个类:第二种特殊情况:装饰器返回的对象的类型不一定等同于被装饰对象的类型. 对于第一种情况,我们知道对于任何callable的对象都可以进行调用(在对象名称后面使用小括号),callable对象的范围就比较广了

Python decorator装饰器

问题: 定义了一个新函数 想在运行时动态增加功能 又不想改动函数本身的代码 通过高阶段函数返回一个新函数 def f1(x): return x*2 def new_fn(f): #装饰器函数 def fn(x): print ('call ' + f.__name__ + '()') return f(x) return fn #方法1 g1 = new_fn(f1) print (g1(5)) #方法2 f1 = new_fn(f1) #f1的原始定义函数彻底被隐藏了 print (f1(5

Python Decorator分析

decorator本身是一个函数,这个函数的功能是接受被修饰的函数(decorated)作为参数,返回包装函数(wrapper)替换被修饰函数(decorated). @decorator func 等同于 func = decorator(func).大部分情况下wrapper函数必须要和decorated函数具有相同的参数,这样在wrapper函数中可以执行decorated函数,并增加一些拓展流程.基于此decorator的原则如下: 对于自定义decorator,wrapper函数的参数

Python decorator @property

@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性 下面的链接很好的阐述了@property的概念和应用 http://www.jb51.net/article/65052.htm http://python.jobbole.com/81967/