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))

#输出:
#call f1()
#10

装饰器

python内置的@语法就是为了简化装饰器

类似上述的方法2

装饰器的作用

可以极大的简化代码,避免每个函数编写重复性代码

  • 打印日志:@log
  • 检测性能:@performance
  • 数据库事务:@transaction
  • URL路由:@post(‘/register‘)
时间: 2024-07-30 13:49:59

Python decorator装饰器的相关文章

【转】详解Python的装饰器

原文链接:http://python.jobbole.com/86717/ Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现了say_hello()和say_goodbye()两个函数. def say_hello(): print "hello!" def say_goodbye(): print "hello!" # bug here if __name__ == '__main__':

Python 函数装饰器入门

原文链接: --> A guide to Python's function decorators Python功能强劲,语法表现力强,尤其装饰器深深的吸引着我.在设计模式中,装饰器可以在不使用子类的情况下,动态的改变函数,方法以及类的功能.这个功能非常有用,特别在你想扩展函数的功能同时又不想改变原有的函数.的确,我们任意的实现装饰器设计模式,但是,python通过提供简单的语法和特性让装饰器的实现变的如此简单. 在本文中,我将用一组例子来深入浅入python 函数装饰器的功能,所有的例子都是在

关于Python的装饰器(1)

Python的装饰器的概念,一直有点微妙.之前在StackOverflow上看过一篇感觉说明的很清楚的介绍: *A decorator must accept a function as an argument 参考地址: http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484 http://stackoverflow.com

说说Python的装饰器模式与面向切面编程

说说Python的装饰器模式与面向切面编程 今天来讨论一下装饰器.装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用.概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能. 1. 装饰器入门 1.1. 需求是怎么来的? 装饰器的定义很是抽象,我们来看一个小例子. //edit http://www.lai18.com //date 2

8.Python中装饰器是什么?

Python中装饰器是什么? A Python decorator is a specific change that we make in Python syntax to alter functions easily. Python decorator是我们在Python语法中使用的一个特定的更改,可以轻松地改变函数. http://www.cnblogs.com/zoe233/p/7070067.html 装饰器定义: 本质是函数.函数的目的是为了完成特定的功能,那么装饰器的功能是什么呢?

python利用装饰器进行运算

今天想用python的装饰器做一个运算,代码如下 >>> def mu(x): def _mu(*args,**kwargs): return x*x return _mu >>> @mu def test(x,y): print '%s,%s' %(x,y) >>> test(3,5) Traceback (most recent call last):   File "<pyshell#111>", line 1, 

详解Python的装饰器

Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现了say_hello()和say_goodbye()两个函数. def say_hello(): print "hello!" def say_goodbye(): print "hello!" # bug here if __name__ == '__main__': say_hello() say_goodbye() 但是在实际调用中,我们

尝试自己的Perl语言的包 TCP协议的再包装起到类似python语言装饰器的效果

#!/usr/bin/perl # Filename: BuildSocketTCP.pm # #   Copyright 2012 Axxeo GmbH #   Licensed under the Apache License, Version 2.0 (the "License"); #   you may not use this file except in compliance with the License. #   You may obtain a copy of t

尝试自己的Perl语言的包 UDP协议的再包装起到类似python语言装饰器的效果

#!/usr/bin/perl # Filename: BuildSocketUDP.pm # #   Copyright 2012 Axxeo GmbH #   Licensed under the Apache License, Version 2.0 (the "License"); #   you may not use this file except in compliance with the License. #   You may obtain a copy of t