1.16 Python基础知识

  Python中的装饰器就是函数,作用就是包装其他函数,为他们起到修饰作用。在不修改源代码的情况下,为这些函数额外添加一些功能,像日志记录,性能测试等。一个函数可以使用多个装饰器,产生的结果与装饰器的位置顺序有关。

  装饰器基本形式:

  @装饰器1

  def 函数1:

    函数体

  相当于:==》  函数1 = 装饰器1(函数1)

  装饰器特点:

  1、不修改源代码的调用方式

  2、不修改源代码内容

  3、装饰器有高阶函数递归函数相融合的特点

  多个装饰器修饰,示例:

@foo
@spam
def bar():pass

相当于:

def bar():pass

bar = foo(spam(bar))

  装饰器示例1(无参数传递):计算程序运行时间

import time
def foo(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print('the func run %s .' % (stop_time - start_time))
    return wrapper

@foo
def bar():
    time.sleep(3)
    print("In the bar.")


bar()

# 输入结果

In the bar.
the func run 3.016378402709961 .

  装饰器示例2(源代码有参数传递):

import time
def foo(func):
    def wrapper(args):
        start_time = time.time()
        func(args)
        stop_time = time.time()
        print('the func run %s .' % (stop_time - start_time))
    return wrapper

@foo
def bar(name):
    time.sleep(3)
    print('Hello %s .' % name)

user_name = input('What is your name ?
')
bar(user_name)

# 输出结果

What is your name ?
zhanghk
Hello zhanghk .
the func run 3.0003373622894287 .

  装饰器示例3(装饰器传递参数):

import time

def foo(n):
    def ac(func):
        def wrapper(args):
            if n == 1:
                start_time = time.time()
                func(args)
                stop_time = time.time()
                print('the func run %s .' % (stop_time - start_time))
            else:
                func(args)
        return wrapper
    return ac


@foo(n = 0)    # 由"n"是否等于1来判断是否计算程序运行时间
def bar(name):
    time.sleep(3)
    print('Hello %s .' % name)

user_name = input('What is your name ?
')
bar(user_name)

# 输出结果

What is your name ?
zhanghk
Hello zhanghk .
原文地址:https://www.cnblogs.com/topspeedking/p/6541347.html