当前位置:首页 » python教程 » 正文

Python新手学习装饰器

看: 870次  时间:2020-06-25  分类 : python教程

python函数式编程之装饰器

1.开放封闭原则

简单来说,就是对扩展开放,对修改封闭。

在面向对象的编程方式中,经常会定义各种函数。一个函数的使用分为定义阶段和使用阶段,一个函数定义完成以后,可能会在很多位置被调用。这意味着如果函数的定义阶段代码被修改,受到影响的地方就会有很多,此时很容易因为一个小地方的修改而影响整套系统的崩溃,所以对于现代程序开发行业来说,一套系统一旦上线,系统的源代码就一定不能够再改动了。然而一套系统上线以后,随着用户数量的不断增加,一定会为一套系统扩展添加新的功能。

此时,又不能修改原有系统的源代码,又要为原有系统开发增加新功能,这就是程序开发行业的开放封闭原则,这时就要用到装饰器了。

2.什么是装饰器

装饰器,顾名思义,就是装饰,修饰别的对象的一种工具。

所以装饰器可以是任意可调用的对象,被装饰的对象也可以是任意可调用对象。

3.装饰器的作用

在不修改被装饰对象的源代码以及调用方式的前提下为被装饰对象添加新功能。

原则:

1.不修改被装饰对象的源代码

2.不修改被装饰对象的调用方式

目标:

为被装饰对象添加新功能。

实例扩展:

import time
# 装饰器函数
def wrapper(func):
 def done(*args,**kwargs):
  start_time = time.time()
  func(*args,**kwargs)
  stop_time = time.time()
  print('the func run time is %s' % (stop_time - start_time))
 return done
# 被装饰函数1
@wrapper
def test1():
 time.sleep(1)
 print("in the test1")
# 被装饰函数2
@wrapper
def test2(name): #1.test2===>wrapper(test2) 2.test2(name)==dome(name)
 time.sleep(2)
 print("in the test2,the arg is %s"%name)
# 调用
test1()
test2("Hello World")

不含参数实例:

import time
user,passwd = 'admin','admin'
def auth(auth_type):
 print("auth func:",auth_type)
 def outer_wrapper(func):
  def wrapper(*args, **kwargs):
   print("wrapper func args:", *args, **kwargs)
   if auth_type == "local":
    username = input("Username:").strip()
    password = input("Password:").strip()
    if user == username and passwd == password:
     print("\033[32;1mUser has passed authentication\033[0m")
     res = func(*args, **kwargs) # from home
     print("---after authenticaion ")
     return res
    else:
     exit("\033[31;1mInvalid username or password\033[0m")
   elif auth_type == "ldap":
    print("ldap链接")
  return wrapper
 return outer_wrapper
@auth(auth_type="local") # home = wrapper()
def home():
 print("welcome to home page")
 return "from home"
@auth(auth_type="ldap")
def bbs():
 print("welcome to bbs page"
print(home()) #wrapper()
bbs()

到此这篇关于Python新手学习装饰器的文章就介绍到这了,更多相关Python之装饰器简介内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!