python代码:装饰器

书《Python核心编程(第二版).pdf》,作者:Wesley J. Chun

装饰器
====
1. 无参数的装饰器
@deco
def foo(): pass
等价于:
foo = deco(foo)

2. 带参数的装饰器
@decomaker(deco_args)
def foo(): pass
等价于:
foo = decomaker(deco_args)(foo)

3. 含有多个装饰器
@deco1(deco_arg)
@deco2
def func(): pass
等价于:
func = deco1(deco_arg)(deco2(func))

4. 装饰器的用途
(1)引入日志
(2)增加计时逻辑来检测性能
(3)给函数加入事务的能力
 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:
@file:deco.py
@time:2022-03-09 17:39
"""

# 通过显示函数执行的时间“装饰”了一个函数。即时间戳装饰。
# 例11.2 使用函数装饰器的例子(deco.py)

from time import ctime, sleep

# 显示何时调用函数的时间戳装饰器。
# 它定义了一个内部的函数wrappedFunc(),该函数增加了时间戳以及调用了目标函数。
# 装饰器的返回值是一个“包装了”的函数。
def tsfunc(func):
    def wrappedFunc():
        print('[%s] %s() called' % (ctime(), func.__name__))
        return func()
    return wrappedFunc

@tsfunc
def foo():
    # pass
    print("Hello world!")

foo()
sleep(4)

for i in range(2):
    sleep(1)
    foo()

"""
运行结果如下:
[Wed Mar  9 18:06:58 2022] foo() called
Hello world!
[Wed Mar  9 18:07:03 2022] foo() called
Hello world!
[Wed Mar  9 18:07:04 2022] foo() called
Hello world!
"""

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值