码迷,mamicode.com
首页 > 编程语言 > 详细

python\装饰器

时间:2017-04-12 17:25:48      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:调用   不同   class   for   font   基本   传递   style   soft   

一.基本装饰器

基本装饰器的作用:

    在不改变原函数的基础上, 通过装饰器, 给原函数新增某些功能

  实现方法:

    在原函数上加

      @装饰器名字

      其中@叫做语法糖

    定义装饰器

      第一层函数传入参数(用于传入原函数)

      第二层使用原函数的同时, 加入需要新增的功能

      第一层函数要返回第二层函数名

      整个函数形成闭包

import time

 def runtime(func):
    def wrapper():
        start = time.time()
        for in range(100):
            func()
        end = time.time()
        print("程序运行时间为 {} ".format((end - start)/1000.0))
    return wrapper
 
@runtime
def hello():
    print("hello world")
 
hello()
 
二.三层装饰器

现在需要在装饰器的基础上, 调用 @装饰器 的时候传入参数

就需要在原有的装饰器的基础上, 在外层写一个函数, 从而又形成闭包的结构

import time
 def runtime(msg="默认值"):
    def decorator(func):
        def wrapper():
            start = time.time()
            for in range(100):
                func()
            end = time.time()
            print(msg)
            print("程序运行时间为 {} ".format((end - start) / 1000.0))
        return wrapper
    return decorator
 
@runtime("hello()")
def hello():
    print("hello world")
 
hello()

三.完善参数传递

在之前的装饰器中, 由于原函数可能存在不同种类的参数, 可能有各种各样的返回值, 所以要进行一下两点修改

    1 将装饰器实际执行函数的参数设置为(*, **)的形式

    2 改函数需要return 原函数

import time
 
def log(msg="默认值"):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(func.__name__, msg)
            return func(*args, **kwargs)
        return wrapper
    return decorator
 
@log("hello()")
def hello():
    print("hello world")
 
hello()

python\装饰器

标签:调用   不同   class   for   font   基本   传递   style   soft   

原文地址:http://www.cnblogs.com/asaka/p/6700265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!