温馨提示×

温馨提示×

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

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

浅谈Python装饰器

发布时间:2020-07-18 15:41:35 来源:亿速云 阅读:101 作者:小猪 栏目:开发技术

小编这次要给大家分享的是浅谈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装饰器的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

向AI问一下细节

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

AI