首页 > 代码库 > 装饰器

装饰器

有参数的装饰器

def deco(arg):           #装饰器的参数
    def _deco(func):     #函数名
        def __deco(x):   #函数的参数
            print("before %s called [%s]." % (func.__name__, arg))
            s = func(x)
            print("after %s called [%s]." % (func.__name__, arg))
            return s
        return __deco
    return _deco

@deco("module")
def myfunc(x):
    print("myfunc() called.")
    return x ** 2

s = myfunc(14)
print(s)

# before myfunc called [module].
# myfunc() called.
# after myfunc called [module].
# 196

  

装饰器