博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python
阅读量:2070 次
发布时间:2019-04-29

本文共 1409 字,大约阅读时间需要 4 分钟。

1.装饰器解析

@ 符号就是装饰器的语法糖,它放在函数开始定义的地方,这样就可以省略最后一步再次赋值的操作。

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

使用:装饰器多用于授权于日志

装饰器函数

from functools import wrapsdef main(func):    print('is main function...')    @wraps(func)    def child():        print('it print before exec func...')        func()        print('it print after exec func...')    return child@maindef alone():    print("I'm  alone function ...")    print(alone.__name__)alone()

装饰器类

from functools import wraps class logit(object):    def __init__(self, logfile='out.log'):        self.logfile = logfile     def __call__(self, func):        @wraps(func)        def wrapped_function(*args, **kwargs):            log_string = func.__name__ + " was called"            print(log_string)            # 打开logfile并写入            with open(self.logfile, 'a') as opened_file:                # 现在将日志打到指定的文件                opened_file.write(log_string + '\n')            # 现在,发送一个通知            self.notify()            return func(*args, **kwargs)        return wrapped_function     def notify(self):        # logit只打日志,不做别的        pass

2.利用装饰器为类属性重新赋值

class Person:    def __init__(self):        self._first_name = None    def p(self):        print(self.first_name)//内部调用时需去掉前下划线    @property    def first_name(self):        if not self._first_name:            self._first_name = 'wang'            return self._first_name     a = Person()a.p()

转载地址:http://uwjmf.baihongyu.com/

你可能感兴趣的文章
Go语言学习Part1:包、变量和函数
查看>>
Go语言学习Part2:流程控制语句:for、if、else、switch 和 defer
查看>>
Go语言学习Part3:struct、slice和映射
查看>>
Go语言学习Part4-1:方法和接口
查看>>
Leetcode Go 《精选TOP面试题》20200628 69.x的平方根
查看>>
Leetcode C++ 剑指 Offer 09. 用两个栈实现队列
查看>>
Leetcode C++《每日一题》20200707 112. 路径总和
查看>>
云原生 第十一章 应用健康
查看>>
Leetcode C++ 《第202场周赛》
查看>>
云原生 第十二章 可观测性:监控与日志
查看>>
Leetcode C++ 《第203场周赛》
查看>>
云原生 第十三章 Kubernetes网络概念及策略控制
查看>>
《redis设计与实现》 第一部分:数据结构与对象 || 读书笔记
查看>>
《redis设计与实现》 第二部分(第9-11章):单机数据库的实现
查看>>
算法工程师 面经2019年5月
查看>>
搜索架构师 一面面经2019年6月
查看>>
稻草人手记
查看>>
第一次kaggle比赛 回顾篇
查看>>
leetcode 50. Pow(x, n)
查看>>
leetcode 130. Surrounded Regions
查看>>