0
点赞
收藏
分享

微信扫一扫

Python 装饰器的应用---信息获取

律楷粑粑 2022-02-18 阅读 57
python
# !/usr/bin/env python
# -*- coding:utf-8 -*-

"""
实现一个装饰器,每次调用函数时,将函数名以及调用此函数的时间节点写入文件decorator中。
"""
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()

举报

相关推荐

0 条评论