详解Python装饰器

yipeiwu_com6年前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设计】网站的支持!

相关文章

Python使用functools模块中的partial函数生成偏函数

python 中提供一种用于对函数固定属性的函数(与数学上的偏函数不一样) # 通常会返回10进制 int('12345') # print 12345 # 使用参数 返回 8...

深入解析Python编程中JSON模块的使用

JSON编码支持的基本数据类型为 None , bool , int , float 和 str , 以及包含这些类型数据的lists,tuples和dictionaries。 对于di...

利用Pandas 创建空的DataFrame方法

平时写pyhton的时候习惯初始化一些list啊,tuple啊,dict啊这样的。一用到Pandas的DataFrame数据结构也就总想着初始化一个空的DataFrame,虽然没什么太大...

Python3实现将本地JSON大数据文件写入MySQL数据库的方法

本文实例讲述了Python3实现将本地JSON大数据文件写入MySQL数据库的方法。分享给大家供大家参考,具体如下: 最近导师给了一个yelp上的评论数据,数据量达到3.55个G,如果进...

python更新列表的方法

本文实例讲述了python更新列表的方法。分享给大家供大家参考。具体如下: aList = [123, 'abc', 4.56, ['inner', 'list'], (7-9j)]...