# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
实现一个装饰器,每次调用函数时,将函数名以及调用此函数的时间节点写入文件info_myfunc中。
"""
import time
# 获取函数调用时间和函数名的装饰器
def get_info_decorator(func):
def inner(*args, **kwargs):
ret = func(*args, **kwargs)
with open('info_myfunc', encoding='utf-8', mode='a') as f:
time_call = time.localtime()
now_time = time.strftime("%Y-%m-%d %H:%M:%S", time_call)
f.write(f'{now_time}调用了函数{func.__name__}\n')
return ret
return inner
@get_info_decorator
def myfunc():
print("Hello World!!!")
myfunc()
Python 装饰器的应用---信息获取
于 2022-02-18 14:35:01 首次发布