装饰器:本质是函数,用于装饰其他函数,在不改变其他函数的调用和代码的前提下,增加新功能

原则:

1.不能修改被装饰函数的源代码

2.不能修改被装饰函数的调用方式

3.装饰函数对于被装饰函数透明

参考如下链接:

http://egon09.blog.51cto.com/9161406/1836763

实现装饰器的需求:

  1. 函数即“变量”,函数名指向内存中的函数体,加()表示调用
  2. 高价函数,将函数当做参数传递给其他函数
  3. 嵌套函数,在函数体内再定义函数

1.调用简单的函数:

import time
def test1():
    time.sleep(1)
    print('in the test1')
test1()

output: 
in the test1

2.在不改变原来函数的定义和调用方式,增加计时功能

import time
def timmer(func):
    def warpper(*args,**kwargs):
        start_time=time.time()
        func()
        stop_time=time.time()
        print('the func run time is %s' %(stop_time-start_time))
    return  warpper

@timmer
def test1():
    time.sleep(1)
    print('in the test1')
test1()

output:
in the test1
the function run time is -1.0007600784301758:
# /usr/bin/env python
# -*- coding: utf-8 -*-
# Author:Jenvid.yang
# def foo():
#     print('in the foo')
#     bar()
# foo()
# bar() 未定义,肯定会报错

# def bar():
#     print('in the bar')
# def foo():
#     print('in the foo')
#     bar()
# foo()

# def foo():
#     print('in the foo')
#     bar()
# def bar():
#     print('in the bar')
# foo()
# 定义函数的时候,只是用函数名指向内存地址,只要函数执行步骤在函数定义之后即可,各函数间前后关系不影响

# def foo():
#     print('in the foo')
#     bar()
# foo()
# def bar():
#     print('in the bar')
函数名及调用关系

相关文章:

  • 2021-08-27
  • 2021-08-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-02
  • 2021-10-01
  • 2021-12-10
  • 2022-01-26
  • 2021-08-29
  • 2021-10-30
  • 2021-11-29
相关资源
相似解决方案