python基础-装饰器decorator

2022-07-31,,,

装饰器介绍目录

  • 什么是装饰器?
  • 装饰器实例
    • 1、无参数函数---计时装饰器
    • 2、有参数函数
    • 3、有参数装饰器

什么是装饰器?

定义:本质是函数,用于装饰其他函数,就是为其他函数添加附加功能

原则:
1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式

实现装饰器知识储备:
1.函数即“变量”
2.高阶函数

什么高阶函数:
			把一个函数名当作实参传给另外一个函数(不修改被装饰函数的情况下为其添加功能)
			返回值中包含函数名(不修改函数的调用方法)

3.嵌套函数

就是在一个函数里用def定义另外一个函数

装饰器实例

1、无参数函数—计时装饰器

import time

def timmer(func):					#func = test1
	def warpper():
		start_time = time.time()
		func()						#运行test1()
		stop_time = time.time()
		print('The function run time is %s' %(stop_time-start_time))
	return warpper
		
@timmer			#test1 = timmer(test),相当于test1 = warpper
def test1():
	time.sleep(2)
	print('In the test1')

if __name__ == "__main__":
	test1()

2、有参数函数

import time

def timmer(func):					#func = test1
	def warpper(*args,**kwargs):
		start_time = time.time()
		func(*args,**kwargs)						#运行test1()
		stop_time = time.time()
		print('The function run time is %s' %(stop_time-start_time))
	return warpper
		
@timmer			#test1 = timmer(test),相当于test1 = warpper
def test1(name):
	time.sleep(2)
	print('My Name is %s' %name)

if __name__ == "__main__":
	name = 'Hua'
	test1(name)

3、有参数装饰器

user = 'hua'
password = '123456'

def auth(auth_type):
    def outer_rapper(func):
        def wrapper(*args,**kwargs):
            
            use = input('user:')
            pswd = input('password:')

            if auth_type == 'local':
                if use == user and pswd == password:
                    func()
            
            elif auth_type == 'ldap':
                print('从ldap查找账户密码。。。')
                func()

        return wrapper
    return outer_rapper

def index():
    print('index page!')

@auth(auth_type = 'local')
def home():
    print('home page!')

@auth(auth_type = 'ldap')
def edit():
    print('edit page!')

if __name__ == "__main__":
    
    index()
    print('-'*30)
    home()
    print('-'*30)
    edit()

本文地址:https://blog.csdn.net/q79815321/article/details/107647346

《python基础-装饰器decorator.doc》

下载本文的Word格式文档,以方便收藏与打印。