Python3 中的装饰器

先说一下,Python3中的装饰器优点:在不修改原本函数内容前提下,可以对功能进行扩展。比如说:你的前队友已经写好了这个函数,一旦你通过修改这函数来做功能扩展,肯定会出现bug的,所以就得用到 Python3 中的装饰器。

其实Python3的装饰器本质上是利用了

  • 嵌套 + 闭包
  • @xx语法

代码例子

def outer(func):
	def inner():
		# 在这里可以添加你要的功能

		res = func() # 这是调用原本的函数

		# 在这里也可以添加你要的功能
	
		return res
	return inner 

@outer    # 其实这个叫法是 show = outer(show)
def show():
	print("show function")
	return 11

v1 = show()
print(v1)

举个例子

import time 

def calculateTime(func):
    def inner():
        start = time.time()
        res = func()
        end = time.time()
        interval = start - end 
        print(f"the function name {func}, the time interval: {interval}")
        return res 
    return inner 

@calculateTime
def f1():
    for i in range(99999):
        pass 


def f2():
    for i in range(10000):
        pass

f1()
f2()

# 输出结果
# 结果完全符合预期,只有函数 f1 才用了 calculateTime 函数
the function name <function f1 at 0x0000020D3EABA160>, the time interval: -0.001027822494506836


第二个例子

import os 

def checkFile(func):
	def inner(file_path):
		if not os.path.exists(file_path):
			return None 
		res = func(file_path)
		return res 
	return inner 

@checkFile
def readFile(file_path):
	f = open(file_path. mode='r', encoding='utf-8')
	data = f.read()
	f.close()
	return data

print(read_info("test.txt"))


给个赞呗~

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值