02python 装饰器(python函数)

装饰器的形成过程

import time

def func(): # 定义一个函数
time.sleep(0.01)
print(‘hello world!‘)

def timer(f): # 一个闭包函数,接收一个函数,也叫做装饰器函数
def inner():
start = time.time()
f() # 被装饰函数
end = time.time()
print(end - start)
return inner

func = timer(func)
func()

20

1

import time

2


3


4

def func():                      # 定义一个函数

5

    time.sleep(0.01)

6

    print(‘hello world!‘)

7


8


9

def timer(f):                    # 一个闭包函数,接收一个函数,也叫做装饰器函数

10

    def inner():

11

        start = time.time()

12

        f()                      # 被装饰函数

13

        end = time.time()

14

        print(end - start)

15

    return inner

16


17


18

func = timer(func)

19

func()

20





装饰器的定义:把接收函数作为参数,以及返回内部函数的函数称之为装饰器函数


语法糖的概念

import time

def timer(f): # 一个闭包函数,接收一个函数,也叫做装饰器函数
def inner():
start = time.time()
f() # 被装饰函数
end = time.time()
print(end - start)
return inner

@timmer # 语法糖 @装饰器函数名
def func(): # 被装饰函数 # 定义一个函数 # func = timer(func)
time.sleep(0.01)
print(‘hello world!‘)

# func = timer(func)
func() # 在调用的时候只要调用func()即可!这才是装饰器

20

1

import time

2


3


4

def timer(f):                    # 一个闭包函数,接收一个函数,也叫做装饰器函数

5

    def inner():

6

        start = time.time()

7

        f()                      # 被装饰函数

8

        end = time.time()

9

        print(end - start)

10

    return inner

11


12


13

@timmer                          # 语法糖 @装饰器函数名

14

def func():                      # 被装饰函数   # 定义一个函数   # func = timer(func)

15

    time.sleep(0.01)

16

    print(‘hello world!‘)

17


18

    

19

# func = timer(func)

20

func()                           # 在调用的时候只要调用func()即可!这才是装饰器
再次进化        (被装饰的函数有返回值)

55

1

import time

2


3


4

def timer(f):

5

    def inner():

6

        start = time.time()

7

        f()

8

        end = time.time()

9

        print(end - start)

10

    return inner

11


12


13

@timer

14

def func():

15

    time.sleep(0.01)

16

    print(‘hello world!‘)

17

    return ‘pontoon on the way!’

18


19

ret = func()

20

print(ret)

21


22

>>>hello world!

23

0.010217905044555664

24

None        # 打印的结果是None,而不是pontoon on the way!,因为这里接收的是inner函数里面的返回值,而inner函数里面并没有返回值

25


26


27

-------------------------------------------------------------------------------------------------------------------------------------------------------

28

import time

29


30


31

def timer(f):

32

    def inner():

33

        start = time.time()

34

        ret = f()                   # 得到传递过来函数的返回值

35

        end = time.time()

36

        print(end - start)

37

        return ret                  # 返回

38

    return inner

39


40


41

@timer

42

def func():

43

    time.sleep(0.01)

44

    print(‘hello world!‘)

45

    return ‘pontoon on the way!‘

46


47


48

# func = timer(func)

49

ret = func()

50

print(ret)

51


52

>>>hello world!

53

0.010081291198730469

54

pontoon on the way!

55





究极进化        (被装饰的函数有参数)

import time

def timer(f):
def inner(*args, **kwargs):
start = time.time()
ret = f(*args, **kwargs) # 得到传递过来函数的返回值
end = time.time()
print(end - start)
return ret # 返回
return inner

@timer
def func(a, b):
time.sleep(0.01)
print(‘hello world!‘)
return ‘pontoon on the way!‘

# func = timer(func)
ret = func(1, 2) # 这里相当于执行inner()
print(ret)

-----------------------------------------------------------------------------------------------
# 简化之
import time

def wrapper(f):
def inner(*args, **kwargs):
ret = f(*args, **kwargs) # 得到传递过来函数的返回值
return ret # 返回
return inner

@wrapper
def func(a, b):
time.sleep(0.01)
print(‘hello world!‘)
return ‘pontoon on the way!‘

# func = timer(func(1, 2))
ret = func(1, 2) # 这里相当于执行inner()
print(ret)

至此简化版的装饰器OK了!

49

1

import time

2


3


4

def timer(f):

5

    def inner(*args, **kwargs):

6

        start = time.time()

7

        ret = f(*args, **kwargs)        # 得到传递过来函数的返回值

8

        end = time.time()

9

        print(end - start)

10

        return ret                      # 返回

11

    return inner

12


13


14

@timer

15

def func(a, b):

16

    time.sleep(0.01)

17

    print(‘hello world!‘)

18

    return ‘pontoon on the way!‘

19


20


21

# func = timer(func)

22

ret = func(1, 2)                        # 这里相当于执行inner()

23

print(ret)

24


25

-----------------------------------------------------------------------------------------------

26

# 简化之

27

import time

28


29


30

def wrapper(f):

31

    def inner(*args, **kwargs):

32

        ret = f(*args, **kwargs)        # 得到传递过来函数的返回值

33

        return ret                      # 返回

34

    return inner

35


36


37

@wrapper

38

def func(a, b):

39

    time.sleep(0.01)

40

    print(‘hello world!‘)

41

    return ‘pontoon on the way!‘

42


43


44

# func = timer(func(1, 2))

45

ret = func(1, 2)                        # 这里相当于执行inner()

46

print(ret)

47


48


49

至此简化版的装饰器OK了!

装饰器的作用

在不修改原函数及其调用方式的情况下对原函数的功能进行拓展

原则:开放闭合原则

  开放:对拓展时开放的

  封装:对修改是封闭的

装饰器的固定模式

def wrapper(f):
def inner(*args, **kwargs):
ret = f(*args, **kwargs) # 被装饰的函数要有接收的参数并且有返回值!
return ret
return inner

@wrapper
def qqxing():
print(123)

print(qqxing())

x

1

def wrapper(f):

2

    def inner(*args, **kwargs):

3

        ret = f(*args, **kwargs)          # 被装饰的函数要有接收的参数并且有返回值!

4

        return ret

5

    return inner

6


7


8

@wrapper

9

def qqxing():

10

    print(123)

11


12


13

print(qqxing())

装饰器的进阶

1、带参数的装饰器

2、多个装饰器装饰同一个函数

span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }.cm-searching {background: #ffa; background: rgba(255, 255, 0, .4);}.cm-force-border { padding-right: .1px; }@media print { .CodeMirror div.CodeMirror-cursors {visibility: hidden;}}.cm-tab-wrap-hack:after { content: ""; }span.CodeMirror-selectedtext { background: none; }.CodeMirror-activeline-background, .CodeMirror-selected {transition: visibility 0ms 100ms;}.CodeMirror-blur .CodeMirror-activeline-background, .CodeMirror-blur .CodeMirror-selected {visibility:hidden;}.CodeMirror-blur .CodeMirror-matchingbracket {color:inherit !important;outline:none !important;text-decoration:none !important;}.CodeMirror-sizer {min-height:auto !important;}
-->
li {list-style-type:decimal;}.wiz-editor-body ol.wiz-list-level2 > li {list-style-type:lower-latin;}.wiz-editor-body ol.wiz-list-level3 > li {list-style-type:lower-roman;}.wiz-editor-body blockquote {padding: 0 12px;}.wiz-editor-body blockquote > :first-child {margin-top:0;}.wiz-editor-body blockquote > :last-child {margin-bottom:0;}.wiz-editor-body img {border:0;max-width:100%;height:auto !important;margin:2px 0;}.wiz-editor-body table {border-collapse:collapse;border:1px solid #bbbbbb;}.wiz-editor-body td,.wiz-editor-body th {padding:4px 8px;border-collapse:collapse;border:1px solid #bbbbbb;min-height:28px;word-break:break-word;box-sizing: border-box;}.wiz-hide {display:none !important;}
-->

原文地址:https://www.cnblogs.com/pontoon/p/10238331.html

时间: 2024-08-02 22:11:25

02python 装饰器(python函数)的相关文章

关于Python装饰器内层函数为什么要return目标函数的一些个人见解

https://blog.csdn.net/try_test_python/article/details/80802199 前几天在学装饰器的时候,关于装饰器内层函数调用目标函数时是否return目标函数的调用产生了一点迷惑,事实是当被装饰的目标函数有返回值的时候,装饰器内层函数也必须返回该目标函数的调用. 我们都知道不带括号的函数名指向是函数代码所在的内存地址,加上括号之后就变成了一个执行命令,那么这个'func( )'到底有什么意义呢? 上面这张图可以大概看出点东西,单独的函数名是 fun

装饰器工厂函数

""" 需求:参数传入0 希望时间用整数显示,参数传入1 用浮点数显示 """ import time def get_run_time(flag): """装饰器工厂函数""" def get_time(func): """装饰器函数:对函数运行时间进行统计""" print('in get_time') def inner(

diango中让装了装饰器的函数的名字不是inner,而是原来的名字

让装了装饰器的函数的名字不是inner,而是原来的名字 from functools import wraps def wrapper(func): @wraps(func) # 复制了原来函数的名字和注释 def inner(request,*arg,**kwargs): # 之前 ret = func(request,*arg,**kwargs) # 之后 return ret return inner @wrapper # f1 = wrapper(f1) def f1(request):

python笔记--3--函数、生成器、装饰器、函数嵌套定义、函数柯里化

函数 函数定义语法: def 函数名([参数列表]): '''注释''' 函数体 函数形参不需要声明其类型,也不需要指定函数返回值类型 即使该函数不需要接收任何参数,也必须保留一对空的圆括号 括号后面的冒号必不可少 函数体相对于def关键字必须保持一定的空格缩进 Python允许嵌套定义函数 在定义函数时,开头部分的注释并不是必需的,但是如果为函数的定义加上这段注释的话,可以为用户提供友好的提示和使用帮助. Python是一种高级动态编程语言,变量类型是随时可以改变的.Python中的函数和自定

Python学习(十)—— 装饰器和函数闭包

装饰器 装饰器:本质就是函数,功能是为其他函数添加附加功能 原则: 1.不修改被修饰函数的源代码 2.不修改被修饰函数的调用方式 统计程序运行的时间(不使用装饰器): 这种方法修改了源代码,不能用于已经上线的程序 1 import time 2 def calc(l): 3 res = 0 4 start_time = time.time() 5 for i in l: 6 res += i 7 time.sleep(0.01) 8 stop_time = time.time() 9 print

使用装饰器进行函数类型检查

动态类型的特性使得Python函数在被调用时,其参数类型不易被知晓.或者,为了动态支持多类型,实际参数的类型由调用者提供.如下: def add(x, y): return x + y print(add(2, 3)) # 5 print(add('Hello', ' World')) # Hello World 上面的例子可以看出,函数参数并没有指定类型,使得该函数支持多种类型,这也正是Python语言的特殊之处. 但有时候,我们想限制函数的参数类型.这时很多人会想到类型提示(Type Hin

装饰器(函数)

闭包 1.作用域L_E_G_B(局部.内嵌.全局...): 1 x=10#全局 2 3 def f(): 4 a=5 #嵌套作用域 5 def inner(): 6 count = 7 #局部变量 7 print a 8 return 1 从内往外寻找 a . 2.高阶函数 a.函数名可以作为参数输入 b.函数名可以作为返回值 3.闭包 1 def outer(): 2 x=10 3 def inner(): #条件1 inner是内部函数 4 print(x) #条件2 外部环境的一个变量 5

装饰器与函数的多层嵌套

# coding: utf-8 def login(func): print("the first level") def inner1(*args): print("the second level") def inner2(*args): print("the third level") def inner3(*args): print("the forth level") func(*args) func(*args)

python函数装饰器

学习装饰器前提需要了解高阶函数,函数嵌套,函数闭包 python函数装饰器,顾名思义就是装饰函数,为函数添加新功能的的一种方式. 为什么要使用装饰器呢? 因为函数在运行时,如果不使用装饰器对函数进行功能添加,需要修改函数源代码,这样修改无疑会增加程序的冗余和复杂性,也不便于程序员对其进行修改.使用装饰器,可以在不改变函数源代码和调用方式的前提下,使用语法糖@装饰器,对函数功能进行添加. 装饰器本质上就是一个函数. 我们使用一个简单的例子来实现: import time #这是一个装饰器函数名为t