首页 > 编程语言 > 详细

python-装饰器

时间:2019-12-13 10:21:04      阅读:75      评论:0      收藏:0      [点我收藏+]

装饰器:

定义:本质就是函数,(装饰其他函数)为了其他函数添加功能;

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

    以上两点其实就是装饰器对被他装饰的函数是完全透明的,也就是说用你函数的人不知道你改了这个函数的。

需要用到的知识:

  1、函数即“变量”;2、高阶函数;3、嵌套函数

  高阶函数+嵌套函数 =》装饰器

1、函数即变量----函数定义和变量定义一样,当定义一个函数或者变量时,在内存中放入变量的值或者函数体,变量名或者函数名知识相当于该内存块的门牌号

def bar():            #python中bar函数在foo之前和之后定义都是一样的,只要bar在调用之前存在了就可以;不同于C++;
print(‘in the bar‘)

def foo():
print(‘in the foo‘)
bar()

foo()

2、高阶函数---满足条件:
  a、把一个函数名当着实参传给另外一个函数;(在不修改被装饰函数源代码的情况下为其添加功能)
  b、返回值中包含函数名;两个条件任意一个条件之一就是高阶函数(不修改函数调用方式)。
   a、
    import time

    def bar(): #python中bar函数在foo之前和之后定义都是一样的;不同于C++
    time.sleep(3)
     print(‘in the bar‘)

    def foo(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print(‘the func run time is %s‘%(stop_time-start_time))

    foo(bar)
    b、
    import time

    def bar():
    time.sleep(3)
    print(‘in the bar‘)

    def foo2(func):
    return func

    foo2(bar)()
3、嵌套函数
  def foo():
  def bar():
  print(‘in the bar‘)
  bar()
  print(‘in the foo‘)

  foo()
4、实现装饰器: 高阶函数+嵌套函数
简单版(不带参数):
import time

def timer(func):
def deco():
start_time = time.time()
func()
stop_time = time.time()
print(‘the func run time is %s‘%(stop_time-start_time))
return deco

@timer #@timer 相当于就是test1 = timer(test1);此时test1=deco,deco里面的func=最开始的test1
def test1():
time.sleep(3)
print(‘in the test1‘)
@timer #@timer 相当于就是test2 = timer(test2);此时test2=deco,deco里面的func=最开始的test2
def test2():
time.sleep(5)
print(‘in the test2‘)

test1()
test2()
高级版(带参数):
user,passwd = ‘shimeng‘,‘abc123‘

def auth(auth_type):
def outher_wrapper(func):
def wrapper(*args, **kwargs):
username = input("username:").strip()
password = input("password:").strip()

if auth_type == "local":
if user == username and passwd == password:
print("\033[032;1mUser has passed authentication\033[0m")
return func(*args,**kwargs)
else:
exit("\033[031;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("搞毛线哦,不会了")
else:
print("没有类型")
return wrapper
return outher_wrapper
def index():
print(‘welcome to index page‘)

@auth(auth_type = "local")
def home():
print(‘welcome to home page‘)
@auth(auth_type = "ldap")
def bbs():
print(‘welcome to bbs page‘)

index()
home()
bbs()


python-装饰器

原文:https://www.cnblogs.com/loverb1026/p/12012625.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!