首页 新闻 会员 周边

Python的装饰器怎么装饰其他模块的函数?

0
[已解决问题] 解决于 2017-07-27 16:06

暂时还没学到类,现在有个需求

我在a.py中写了一个装饰器@login,b.py中定义了个函数func()
我在a中怎么用装饰器去装饰这个func()呢

DoubleT的主页 DoubleT | 菜鸟二级 | 园豆:204
提问于:2017-07-15 17:27
< >
分享
最佳答案
-1
import types


def deco(*args):
    def _deco(func):
        def __deco():
            print("before %s called [%s]." % (func.__name__, args))
            func()
            print("  after %s called [%s]." % (func.__name__, args))

        return __deco

    # 当直接使用 @deco 定义的时候第一个参数为函数
    if len(args) == 1 and type(args[0]) is types.FunctionType:
        return _deco(args[0])

    return _deco


def bfunc(func):
    print("before login() called.")
    func()
    print("  after login() called.")
    return func


@deco
def login():
    print(" login() called.")


login()
login()

 http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html  装饰器的各种玩法

奖励园豆:5
悟行 | 专家六级 |园豆:12559 | 2017-07-17 09:21
其他回答(1)
0

前不久整理的装饰器的随笔,希望对您有帮助:http://www.cnblogs.com/0bug/p/7978595.html

0bug | 园豆:149 (初学一级) | 2017-12-06 11:17
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册