当前位置:网站首页>装饰器函数与类装饰器的使用
装饰器函数与类装饰器的使用
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)
边栏推荐
猜你喜欢

Constraints and design of database

互联网简单协议概括

ROS distributed communication

Seven sorting details

wireshark IP地址域名解析

Brief introduction to unity window interface

Li Kou daily question (linked list simulation)

Multi coordinate transformation

If conditional statement of shell

Progress in remote sensing image recognition 2022/5/5
随机推荐
This is my blog
Brief introduction to unity window interface
FTP服务器的搭建
Knowledge supplement of multithreading
shell脚本之函数调用
OSG environment construction (win10+vs2019)
Function call of shell script
Allow or prohibit connecting to a non domain and a domain network at the same time
Linu性能调优:面对DDOS攻击,我们如何缓解局面?
Remote access and control
If conditional statement of shell
Database commands
Non photorealistic rendering (NPR) paper understanding and reproduction (unity) - stylized highlights for cartoon rendering and animation
Compatibility test knowledge points
多线程的相关知识
数组及下标索引
DNS domain name resolution service
多线程常见锁的策略
Unityshader depth texture (understanding and problems encountered)
七大排序详解