实习总结3.2(python部分)

线程与进程 参考 https://blog.csdn.net/liujinen_/article/details/78974275
装饰器 参考 https://www.runoob.com/w3cnote/python-func-decorators.html
内存管理机制 https://www.jb51.net/article/161474.htm
继承机制

在这里插入图片描述
python 装饰器的原理与实现

## 定义一个装饰器 a_func 是被装饰的函数
def a_new_decorator(a_func):
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
##定义一个被装饰的函数
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)    #wrapTheFunction 没有执行
print(a_function_requiring_decoration)
a_function_requiring_decoration() # wrapTheFunction函数执行
#以上就是装饰器的原理
"""
在函数定义前加上使用@装饰器
@装饰器
the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
"""
@a_new_decorator
def a_function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
a_function_requiring_decoration()
print(a_function_requiring_decoration.__name__)  #返回的是wrapTheFunction,不是原来的函数,重写了我们函数的名字和注释文档,可使用functools.wraps来解决

from functools import wraps
 #从functools引入wraps
 #在装饰器函数里加上对被装饰函数的声明 @wraps(a_func)
 #在被装饰函数前,加上装饰声明
def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction
 
@a_new_decorator
def a_function_requiring_decoration():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值