Python Decorator

利用装饰器记录函数运行时间

import datetime
import time
from functools import reduce

class Decorator():
    @staticmethod
    def exectime(func):
        def decor(*arg):
            start = datetime.datetime.now()
            ret = func(*arg)
            print("{} = {}".format(func.__name__, ret))
            end = datetime.datetime.now()
            interval = end - start
            print("{} execution time: {}".format(func.__name__, interval))
            return ret      
        return decor

class Util():
    @staticmethod
    # @Decorator.exectime
    def sum(*arg):
        # slotion 1
        # s=0
        # for i in arg:
        #     # time.sleep(1)
        #     s+=i

        # solution 2
        # head, *remain = arg
        # if remain is None:
        #     return 0
        # return header + sum(remain)
        
        # solution 3
        return reduce(lambda x,y:x+y, arg)
Util.sum(1,2,3)

>> sum = 6
>> sum execution time: 0:00:03.012014

list去空
s=['A', '', 'B', None, 'C', ' ']
s=list(filter(lambda x:x and x.strip(), s))

if x and y or z 等于三元表达式 x?y:z

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 最近学习Python,在看一个框架源码过程中对装饰器很困惑,Google了一圈,在stack overflo...
    dev_xdyang阅读 11,447评论 4 17
  • 文中知识点和代码示例学习自慕课网,python进阶部分(http://www.imooc.com/learn/31...
    SateZheng阅读 4,919评论 0 2
  • 包(lib)、模块(module) 在Python中,存在包和模块两个常见概念。 模块:编写Python代码的py...
    清清子衿木子水心阅读 9,201评论 0 27
  • flask中有很多装饰器,今天来整理下Python中装饰器的相关概念。 1. 最简单的装饰器 我们常常可以看到类似...
    eric6356阅读 4,218评论 0 6
  • 新年快乐,不是祝福,是承诺。——顾漫 《杉杉来吃》 1、概述 2017年过的很快,快到一个实验还没做完就过去了;2...
    纤蹄马阅读 1,534评论 3 2