Python进阶系列(四)

举报
zhulin1028 发表于 2022/06/16 23:48:27 2022/06/16
【摘要】 目录 从函数中返回函数 将函数作为参数传给另一个函数 你的第一个装饰器 从函数中返回函数 其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来: def hi(name="yasoob"):     def greet():    &nbs...

目录

从函数中返回函数

将函数作为参数传给另一个函数

你的第一个装饰器


从函数中返回函数

其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:


  
  1. def hi(name="yasoob"):
  2.     def greet():
  3.         return "now you are in the greet() function"
  4.     def welcome():
  5.         return "now you are in the welcome() function"
  6.     if name == "yasoob":
  7.         return greet
  8.     else:
  9.         return welcome
  10. a = hi()
  11. print(a)
  12. #outputs: <function greet at 0x7f2143c01500>
  13. #上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
  14. #现在试试这个
  15. print(a())
  16. #outputs: now you are in the greet() function

再次看看这个代码。在if/else语句中我们返回greet和welcome,而不是greet()和welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

你明白了吗?让我再稍微多解释点细节。

当我们写下a = hi(),hi()会被执行,而由于name参数默认是yasoob,所以函

数greet被返回了。如果我们把语句改为a = hi(name = "ali"),那么welcome函数将被返回。我们还可以打印出hi()(),这会输出now you are in the greet() function

将函数作为参数传给另一个函数


  
  1. def hi():
  2.     return "hi yasoob!"
  3. def doSomethingBeforeHi(func):
  4.     print("I am doing some boring work before executing hi()")
  5.     print(func())
  6. doSomethingBeforeHi(hi)
  7. #outputs:I am doing some boring work before executing hi()
  8. #        hi yasoob!

现在你已经具备所有必需知识,来进一步学习装饰器真正是什么了。装饰器让你在一个函数的前后去执行代码。

你的第一个装饰器

在上一个例子里,其实我们已经创建了一个装饰器!现在我们修改下上一个装饰器,并编写一个稍微更有用点的程序:


  
  1. def a_new_decorator(a_func):
  2.     def wrapTheFunction():
  3.         print("I am doing some boring work before executing a_func()"       
  4.         a_func()       
  5.         print("I am doing some boring work after executing a_func()"
  6.    
  7.     return wrapTheFunction
  8. def a_function_requiring_decoration():
  9.     print("I am the function which needs some decoration to remove my foul smell")
  10. a_function_requiring_decoration()
  11. #outputs: "I am the function which needs some decoration to remove my foul smell
  12. a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)
  13. #now a_function_requiring_decoration is wrapped by wrapTheFunction()
  14. a_function_requiring_decoration()
  15. #outputs:I am doing some boring work before executing a_func()
  16. #        I am the function which needs some decoration to remove my foul smell
  17. #        I am doing some boring work after executing a_func()

你看明白了吗?我们刚刚应用了之前学习到的原理。这正是python中装饰器做的事情!它们封装一个函数,并且用这样或者那样的方式来修改它的行为。现在你也许疑惑,我们在代码里并没有使用@符号?那只是一个简短的方式来生成一个被装饰的函数。这里是我们如何使用@来运行之前的代码:


  
  1. @a_new_decorator
  2. def a_function_requiring_decoration():
  3.     """Hey you! Decorate me!"""
  4.     print("I am the function which needs some decoration to remove my foul smell")
  5. a_function_requiring_decoration()
  6. #outputs: I am doing some boring work before executing a_func()
  7. #         I am the function which needs some decoration to remove my foul smell
  8. #         I am doing some boring work after executing a_func()
  9. #the @a_new_decorator is just a short way of saying:
  10. a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)

希望你现在对Python装饰器的工作原理有一个基本的理解。如果我们运行如下代码会存在一个问题:


  
  1. print(a_function_requiring_decoration.__name__)
  2. # Output: wrapTheFunction

这并不是我们想要的!Ouput输出应该是“a_function_requiring_decoration”。这里的函数被warpTheFunction替代了。它重写了我们函数的名字和注释文档(docstring)。幸运的是Python提供给我们一个简单的函数来解决这个问题,那就是functools.wraps。我们修改上一个例子来使用


  
  1. functools.wraps:
  2. from functools import wraps
  3. def a_new_decorator(a_func):
  4.     @wraps(a_func)
  5.     def wrapTheFunction():
  6.         print("I am doing some boring work before executing a_func()"
  7.         a_func()
  8.         print("I am doing some boring work after executing a_func()"
  9.     return wrapTheFunction
  10. @a_new_decorator
  11. def a_function_requiring_decoration():
  12.     """Hey yo! Decorate me!"""
  13.     print("I am the function which needs some decoration to remove my foul smell")
  14. print(a_function_requiring_decoration.__name__)
  15. # Output: a_function_requiring_decoration

现在好多了。我们接下来学习装饰器的一些常用场景。

蓝本规范:


  
  1. from functools import wraps
  2. def decorator_name(f):
  3.     @wraps(f)
  4.     def decorated(*args, **kwargs):
  5.         if not can_run:
  6.             return "Function will not run"
  7.         return f(*args, **kwargs)
  8.     return decorated
  9. @decorator_name
  10. def func():
  11.     return("Function is running")
  12. can_run = True
  13. print(func())
  14. # Output: Function is running
  15. can_run = False
  16. print(func())
  17. # Output: Function will not run

注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

文章来源: zhulin1028.blog.csdn.net,作者:zhulin1028,版权归原作者所有,如需转载,请联系作者。

原文链接:zhulin1028.blog.csdn.net/article/details/124410937

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。