温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python装饰器的用法

发布时间:2021-08-12 16:12:30 来源:亿速云 阅读:98 作者:chen 栏目:开发技术

本篇内容主要讲解“Python装饰器的用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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装饰器的用法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI