Python 装饰器(装饰器的简单使用)

简单介绍了装饰器的一些基本内容,包含定义、本质、原则、如何实现。

1、装饰器的定义

定义:一种增加函数功能的简单方法,可以快速地给不同的函数或类插入相同的功能。

简单点就是:高阶函数+嵌套函数 -》装饰器 

2、装饰器本质

本质:函数 ,为其他函数进行装饰。

举个例子,现在有小狗100只,都有吃喝拉撒的功能,此时我想给其中50只小狗戴上装饰帽的功能,这个装饰帽就是装饰器的功能。但是它并不会改变小狗本身原有的功能。

3、装饰器的原则

原则1:不能修改被装饰的函数的源代码

原则2:  不能修改被装饰的函数的调用方式

4、装饰器的实现

大致了解需要有3个步骤:

4.1 函数即变量

4.2 高阶函数

4.3 嵌套函数

举个例子,装饰器count_time()函数实现对one()函数添加统计函数运行时间的功能

 1 import time
 2 def count_time(func):
 3 def deco():
 4 start = time.time()
 5 func()
 6 end = time.time()
 7 print("the func run time  is %s" %(end-start))
 8 return deco
 9 @count_time
10 def one():
11 time.sleep(0.5)
12 print('in the one')
13 one()  //通过语法糖@count_time 直接对one()函数添加统计时间的功能
View Code

详细步骤如下:

4.1函数即变量

举个例子,比如把1赋值给x,内存会为x分配地址,且指向1 ;

此时x赋值给y,y同时也指向1;

 

同理,定义一个test()函数后,调用这个函数test(),内存会为这个函数分配一个地址,并指向函数体

 

4.2 高阶函数

A:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数的源代码情况下为其添加功能)

B:返回值中包含函数名(不修改函数的调用方式)

举个例子,高阶函数代码如下:

1 import time
2 def count_time(func):
3     def deco():
4         start = time.time()
5         func()
6         end = time.time()
7         print("the func run time  is %s" %(end-start))
8     return deco
View Code

4.3 嵌套函数

很简单的一句话:嵌套函数表示的是函数里面有函数

举个例子,one()函数中嵌套two()函数,嵌套函数代码如下:

1 def one():
2     print('in the one')
3     def two():
4         print('in the two')
5     two()
View Code

5、装饰器高级实现

装饰器涉及到有参数的语法糖、无参数的语法糖,后续有时间可以再次进行详细的了解~

 1 user = 'xxx'
 2 password = '123456'
 3 def A(B):
 4     print("B:",B)
 5     def outer_wrapper(func):
 6         def wrapper(*args, **kwargs):
 7             print("wrapper func args:", *args, **kwargs)
 8             if B == "bb":
 9                 user_name = input("Username:")
10                 pass_word = input("Password:")
11                 if user == user_name and password == pass_word:
12                     print("User has passed authentication")
13                     ret = func(*args, **kwargs) 
14                     print("---after authenticaion ")
15                     return ret
16                 else:
17                     exit("Invalid username or password")
18             elif B == "QWW":
19                 print("have question")
20 
21         return wrapper
22     return outer_wrapper
23 
24 def one():
25     print("in the one")
26 @A(B="bb")
27 def two():
28     print("in the two")
29     return " I'm two"
30 
31 @A(B="QWW")
32 def three():
33     print("in the three")
34 
35 one()
36 print(two())
37 three()
View Code
 

猜你喜欢

转载自www.cnblogs.com/wendyw/p/9724231.html