python 装饰器例子

def debug(func):
    def wrapper(word):
        print("[DEBUG]: enter {}()".format(func.__name__))
        return func(word)
    return wrapper

@debug
def say_hello(word):
    print("hello!%s"%(word))

say_hello("hahaha")

 

例子2

def out(func):
    def inner(*args,**kwargs):
        print("这是装饰器啊")
        func(*args,**kwargs)
    # def inner(arg1, arg2):
    #     print("这是装饰器啊")
    #     func(arg1, arg2)
    # return inner()
    return inner

@out
def say(name,age):
    print("我的名字是%s,我今年%d了"%(name,age))

say("张三",20)

注意这里

# return inner()
return inner  ,我一开始写成了 return inner(),这样就丢失参数了,会报错,

你可能感兴趣的:(python)