python - functools中update_wrapper的使用,装饰器的使用,lambda的混合使用

代码如下: 

# coding=utf-8
from functools import update_wrapper
nums = [1, 2, 3, 4, 5, 6]


def run(num):
    """啦啦,我是run函数"""
    num += 1
    print num


def test():
    "哈哈,我是test函数"
    for num in nums:
        # func = lambda: run(num)等同于下面的func函数
        def func():
            "呵呵,我是func函数"
            return run(num)
        update_wrapper(func, run)
        # test.__doc__ = str(num) + 'doc'
        # test.__name__ = str(num) + 'name'
        # func.description = 'desc'
        # print func.description
        # func.hehe = 'desc'
        # print func.hehe
        yield func


if __name__ == "__main__":
    for f in test():
        f()
        print f.__doc__
        print f.__name__
    # print test.__doc__
    # print test.__name__

输出结果:

2
啦啦,我是run函数
run
3
啦啦,我是run函数
run
4
啦啦,我是run函数
run
5
啦啦,我是run函数
run
6
啦啦,我是run函数
run
7
啦啦,我是run函数
run

代码02:

# coding=utf-8
from functools import update_wrapper
nums = [1, 2, 3, 4, 5, 6]


def run(num):
    """啦啦,我是run函数"""
    num += 1
    print num


def test():
    "哈哈,我是test函数"
    for num in nums:
        def func():
            "呵呵,我是func函数"
            return run(num)
        update_wrapper(func, run)
        test.__doc__ = str(num) + 'doc'
        test.__name__ = str(num) + 'name'
        # func.description = 'desc'
        # print func.description
        # func.hehe = 'desc'
        # print func.hehe
        yield func


if __name__ == "__main__":
    for f in test():
        print '*'*10
        f()
        # print f.__doc__
        # print f.__name__
        print test.__doc__
        print test.__name__

输出02:

**********
2
1doc
1name
**********
3
2doc
2name
**********
4
3doc
3name
**********
5
4doc
4name
**********
6
5doc
5name
**********
7
6doc
6name

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值