编程语言
首页 > 编程语言> > Python 装饰器

Python 装饰器

作者:互联网

什么是装饰器

所谓的装饰器,其实就是通过装饰器函数,来修改原函数的一些功能,使得原函数不需要修改。

 

装饰器实现

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

def say_whee():
    print("Whee!")

say_whee = my_decorator(say_whee)

>>> say_whee()
Something is happening before the function is called.
Whee!
Something is happening after the function is called.

 

语法糖(Syntactic Sugar)

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

 

带参数的装饰器

def my_decorator(func):
    def wrapper(people_name):
        print("这是装饰后具有的新输出")
        func(people_name)
    return wrapper

@my_decorator
def hello(people_name):
    print("你好,{}".format(people_name))

hello("张三")

#输出:
#这是装饰后具有的新输出
#你好,张三

 

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("这是装饰后具有的新输出")
        func(*args, **kwargs)
    return wrapper

 

带返回值的装饰器

   def Interrupt_exception(func):
        def wrapper(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
                return result
            except KeyboardInterrupt:
                print("手动停止")
                os._exit(0)
        return wrapper

 

其他更多,详见:把苹果咬哭的测试笔记专栏

标签:Python,wrapper,decorator,func,print,my,装饰,def
来源: https://www.cnblogs.com/QingshanY/p/16325377.html