当前位置:网站首页>装饰器函数与类装饰器的使用
装饰器函数与类装饰器的使用
2022-07-27 05:22:00 【Leoon123】
一、装饰器
装饰器:装饰函数和类,作用:扩展增强函数和类的功能
二、装饰器的分类
两大类:装饰器函数和装饰器类
三、装饰器函数定义及应用
函数:封装代码最小单元,提供代码复用性
装饰器函数利用函数的一些特征:
1、函数可以作为参数
3、函数可以作为变量
2、函数也可以返回函数
装饰器函数实质:调用装饰函数的内置方法
四、装饰器函数的使用
import time
def display_time(fun):
def wrapper():
t1 = time.time()
resutl =fun()
t2 = time.time()
print("总共耗时{:.4} s".format(t2 - t1))
return resutl
return wrapper
def is_price(num):
if num < 2:
return False
elif num == 2:
return True
else:
for i in range(2, num):
if num % i == 0:
return False
return True
'''
相比前面的,多了返回值,
需要在display_time函数中加fun()返回结果
'''
@display_time
def count_prime_number():
count=0
for i in range(2, 1000):
if is_price(i):
count=count+1
return count
counts=count_prime_number()
print(counts)
五、类装饰器的使用
import time
# 定义装饰类‐‐‐‐‐》本质类 作用:原来功能+扩展功能
class A:
# 原来功能 self._func()
def __init__(self, func):
self._func = func
# 扩展功能
def __call__(self, *args, **kwargs):
"""
__call__函数:实例化对象()
:return:
"""
start = time.time()
# 原来功能
result=self._func(*args, **kwargs) # 原来功能
end = time.time()
print("总共耗时{:.4} s".format(end - start))
return result
@A
def count_prime_number(maxnumber):
time.sleep(1)
sum=0
for i in range(2, maxnumber):
sum=sum+i
return sum
sums=count_prime_number(10000)
print(sums)
边栏推荐
- 正确安装wireshark
- Common SQL optimization methods
- 允许或者禁止同时连接到一个non-domain和一个domain网络
- Programming learning records - Lesson 8 [array and design Gobang, minesweeping game]
- Programming learning records - Lesson 3 [first knowledge of C language]
- 5G网络身份识别---详解5G-GUTI
- FTP服务器的搭建
- Remote access and control
- Three ways to get RPM packages using yum
- C language -- string operation function and memory operation function
猜你喜欢
随机推荐
Programming learning records - Lesson 3 [first knowledge of C language]
Related knowledge of multithreading
DNS故障分析优化
软件测试用里篇
Install Wireshark correctly
多线程CAS、synchronized锁原理 、JUC以及死锁
七大排序详解
wireshark数据包修改--添加或修改消息字段(二)
Random points in non overlapping rectangle (force deduction daily question)
shell script if嵌套for循环脚本
Reading and writing of file content - data flow
Shell programming specifications and variables
Basic file operation of cmder
Header and source files in ROS
Addition, deletion, modification and query of the database at the terminal
Allow or prohibit connecting to a non domain and a domain network at the same time
数据库的约束以及设计
Basic concepts of software testing
Programming learning record -- recursively solving the tower of Hanoi problem
[first blog - outlook]









