当前位置:脚本大全 > > 正文

python装饰器使用说明(详解Python装饰器)

时间:2021-10-26 11:07:50类别:脚本大全

python装饰器使用说明

详解Python装饰器

1. 定义

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

2. 原则

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

3. 实现装饰器知识储备

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

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • # 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装饰器详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对开心学习网网站的支持!

    原文链接:https://www.cnblogs.com/lockegogo/p/10591160.html

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐