Python教程

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!")

 

带参数的装饰器

  • 单个参数
  • 上面的只是一个非常简单的装饰器,但是实际场景中,很多函数都是要带有参数的,比如hello(people_name)
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 装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!