详解Python装饰器

2019/7/14 23:25:00

本文主要是介绍详解Python装饰器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 定义

本质是函数,用来装饰其他函数,为其他函数添加附加功能

2. 原则

a. 不能修改被装饰函数的源代码
b. 不能修改被装饰的函数的调用方式

3. 实现装饰器知识储备

a. 函数就是变量
b. 高阶函数
    i. 把一个函数当作实参传给另外一个函数,在不修改被装饰函数源代码情况下为其添加功能
    ii. 返回值中包含函数名, 不修改函数的调用方式
c. 嵌套函数
 高阶函数+嵌套函数==》装饰器

# Author: Lockegogo

user, passwd = 'LK', '130914'
def auth(auth_type):
 print('auth func:', auth_type)
 def outher_wrapper(func):
  def wrapper(*args, **kwargs):
   print('wrapper func:', *args, **kwargs)
   if auth_type == 'local':
    username = input('username:').strip()
    password = input('password:').strip()
    if user == username and password == passwd:
     print('\033[32;1mUser has passed authentication\033[0m')
     res = func(*args, **kwargs)
     return res
    else:
     exit('\033[32;1mInvalid Username or password\033[0m')
   elif auth_type == 'ldap':
    print('ldap,不会')
  return wrapper
 return outher_wrapper

def index():
 print('welcome to index page')
@auth(auth_type='local') # home = outher_wrapper(home)
def home():
 print('welcome to home page')
 return 'from home'
@auth(auth_type='ldap')
def bbs():
 print('welcome to bbs page')

index()
print(home())
bbs()

Decorator

以上所述是小编给大家介绍的Python装饰器详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!



这篇关于详解Python装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程