python --装饰器通俗讲解

装饰器

  • 什么是装饰器?:在不修改源代码和调用方式的基础上给其增加新的功能,多个装饰器可以装饰在同一个函数上
  • Python中的装饰器是你进入Python大门的一道坎;

装饰器特点:

  1. 不改变原函数原代码;
  2. 不改变原函数调用方式;
  3. 给原函数增添新的功能;

示例:

def deco(func):
    def wrapper(*args,**kwargs):
        print ("add new function")
        func()
    return wrapper

@deco #相当于func1=deco(func1)
def func1():
    print('hello world')


讲解:

首先:了解函数func 与 func()的区别?

  1. func为函数的内存id
  2. 内存id+()既可以运行函数--->func()

示例:

def func1():
    print('hello world')
print(func1)
.....运行结果
<function func1 at 0x000000834651FBF8>

其次:变动一下装饰器函数并分析他干了些什么

按代码运行顺序进行分析

#第一步:
def deco(func):   
    def wrapper():
        print ("add new function")
        func()
    return wrapper
#第二步
def func1():
    print('hello world')
#第三步
func2=deco(func1)   
#第四步
func2()

第一步:定义deco函数
第二步:定义func1函数
第三步

①调用deco函数并将func1()函数的内存id以实参传入deco函数

②deco 函数动作一:定义wrapper()函数,wrapper函数内容:
print ("add new function")
使用实参func1=func,即:func1()
注意:wrapper函数只定义,未运行;

③deco函数动作二:返回wrapper函数内存id

④将deco()函数的返回值传递给变量func2 即func2=<function deco..wrapper at 0x0000001A66577048> 即func2=wrapper

第四步:func2()即wrapper()

print ("add new function")
func1()

最后,到了这里我们就大体了解了装饰器的工作原理了,我们再回看前面的装饰器就不难理解啦

其中:Python提供了可变参数*args和关键字参数**kwargs,有了这两个参数,装饰器就可以用于任意目标函数了。


拓展:带参数的装饰器

def default_engine(engine=None):
    def auth(func):
        def deco(*args, **kwargs):
            user = input('user:')
            password = input('password:')
            if engine == 'mysql':
                if user == 'root' and password == 'root':
                    res = func(*args, **kwargs)
                    return res
                else:
                    print('用户名或密码错误')
            else:
                print('没有这个引擎')
        return deco
    return auth

@default_engine(engine='mysql')
def index():
    print('welcome to home page')

# res = default_engine(engine='mysql')
# index = res(index)
index()

原文地址:https://www.cnblogs.com/du-z/p/11046874.html